npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-complex-state

v1.1.0

Published

Introducing useComplexState hook, a small wrapper combining Redux Toolkit, useReducer with some extra syntax sugar to make things even simpler and more to-the-point.

Downloads

260

Readme

Introducing useComplexState hook, a small wrapper combining Redux Toolkit, useReducer with some extra syntax sugar to make things even simpler and more to-the-point.

Why?

useReducer is a low-level counterpart to Redux, but is meant to be used for a much smaller scope (usually a single component). As such, it comes with similar problems that Redux does out of the box - the default code is unnecessarily verbose and difficult to type. Redux Toolkit solves those problems for Redux, but it's not really meant out of the box for useReducer. This package changes that, allowing you to use the best of both worlds.

How?

npm install use-complex-state

And then:

import { useComplexState } from "use-complex-state";

Pass to it an options object in the shape of what createSlice takes. It returns an array with a form:

[state, objectWithActions, dispatch];

note: the dispatch is exposed just in case, but you will most likely not need it

What?

Turn this:

import { useReducer } from "react";
const initialState = { count: 0 };

function reducer(
  state = initialState,
  action: { type: string; payload?: any }
) {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "incrementBy":
      return { count: state.count + action.payload };
    default:
      throw new Error();
  }
}

export default function App() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <div>
      {state.count}
      <button onClick={() => dispatch({ type: "incrementBy", payload: 2 })}>
        2 points!
      </button>
      <button onClick={() => dispatch({ type: "increment" })}>1 point</button>
    </div>
  );
}

Into this:

import { PayloadAction } from "@reduxjs/toolkit";
import { useComplexState } from "use-complex-state";

export default function App() {
  const [state, { incrementBy, increment }] = useComplexState({
    initialState: { count: 0 },
    reducers: {
      increment: (state) => {
        state.count += 1;
      },
      incrementBy: (state, action: PayloadAction<number>) => {
        state.count += action.payload;
      },
    },
  });

  return (
    <div>
      {state.count}
      <button onClick={() => incrementBy(2)}>2 points!</button>
      <button onClick={() => increment()}>1 point</button>
    </div>
  );
}

Comparison with using Redux toolkit and useReducer directly:

import { createSlice, PayloadAction } from "@reduxjs/toolkit";

const initialState = { count: 0 }; // #2
const {
  actions: { increment, incrementBy },
  reducer,
} = createSlice({
  name: "counter", // #1
  initialState, // #2
  reducers: {
    increment: (state) => {
      state.count += 1;
    },
    incrementBy: (state, action: PayloadAction<number>) => {
      state.count += action.payload;
    },
  },
});

function App() {
  const [state, dispatch] = useReducer(reducer, initialState /* #2 */);

  return (
    <div>
      {state.count}
      <button onClick={() => dispatch(incrementBy(2)) /* #3 */}>
        2 points!
      </button>
      <button onClick={() => dispatch(increment()) /* #3 */}>1 point</button>
    </div>
  );
}

The differences are (compare with the use-complex-state example just above):

  1. The name is optional. Since we are not combining multiple slices together, like you would likely do with redux, this is just unnecessary noise.
  2. You pass the initialState just once, and you can define it in-line.
  3. No need to wrap the actions with dispatches. That wrapping is ugly, noise'y, and easy to mess up (no warning if you call the action without a dispatch - might be a confusing bug to debug)

Testing

You might want to use react-testing-library, or even an browser-based tool like cypress (with react component testing) to verify the behavior of your component. If your reducers are super complex and you would like to test them without React context, you can move your slice definition out of your component:

import { PayloadAction } from "@reduxjs/toolkit";
import { useComplexState } from "use-complex-state";

export const sliceOptions = {
  initialState: { count: 0 },
  reducers: {
    increment: (state) => {
      state.count += 1;
    },
    incrementBy: (state, action: PayloadAction<number>) => {
      state.count += action.payload;
    },
  },
};

export default function App() {
  const [state, { incrementBy, increment }] = useComplexState(sliceOptions);

  return (
    <div>
      {state.count}
      <button onClick={() => incrementBy(2)}>2 points!</button>
      <button onClick={() => increment()}>1 point</button>
    </div>
  );
}

Then in your tests you can test it the same way you would test redux toolkit slice:

import { createSlice } from "@reduxjs/toolkit";
import { sliceOptions } from "./App";
const {
  actions: { increment, incrementBy },
  reducer,
} = createSlice(sliceOptions);

test("increase by one", () => {
  expect(reducer({ count: 1 }, increment())).toEqual({ count: 2 });
});

test("increment by two", () => {
  expect(reducer({ count: 1 }, incrementBy(2))).toEqual({ count: 3 });
});

test("multiple actions", () => {
  const actions = [increment(), incrementBy(10), incrementBy(100)];

  expect(actions.reduce(reducer, { count: 0 })).toEqual({ count: 111 });
});

useState vs useReducer (/ use-complex-state)

If you want to learn more about when to use one or the other, take a look at this blog post: xolv.io/dev-notes/choosing-between-use-state-and-use-reducer