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 (
The differences are (compare with the use-complex-state example just above):
The name is optional. Since we are not combining multiple slices together, as you would likely do with redux, this is just unnecessary noise.
You pass the initialState just once, and you can define it in-line.
No need to wrap the actions with dispatches. That wrapping is ugly, noisy, 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 a 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.
Note: We use a prepareSliceOptions wrapper function so you still can get the benefit of TypeScript checks and code-completion on that object. That function takes an object and returns it without any transformation, except for optionally adding a name - because createSlice used for testing will expect that.