You don't always need Redux. Here's how you may use custom hooks instead
React now comes with hooks that can be used to manage state and propagate it throughout your app. In essence—you can do Redux without using Redux! I've been trying to use useState and useContext to manage a large block of state in a React app. In think it's a great alternative to Redux.
Let's write our state manager as a custom React hook. This hook is a thin wrapper around React's useState
hook. Instead of giving a setState()
function, it gives a bunch of setState macros (ie, actions
).
You can use the useAppState()
hook in your React components. It will provide the current state
and the actions
.
The functions in actions
are plain old functions that you can pass down into child components.
You can pass them to event props as-is.
If you need to pass many functions down, it's also possible to simply pass the entire actions
object downwards.
The one essential feature of react-redux is the way the application's state is available to all its descendant components. This can be done with React contexts.
In our useAppState.js
file, we'll export a context created with React.createContext, along with a new custom hook for using the app context.
In your app's root, use the AppContext.Provider component. This makes it possible to use the useAppContext()
hook in child components.
The useAppContext
hook allows you to use the app state anywhere inside the Provider tree. This is similar to using react-redux's connect() function.
Thanks for reading this! I've done a few edits to this article since it was first published:
Changed setState({ ...state })
to setState(state => ({ ...state }))
, because the latter would cause trouble when many setState's are called.
Added useMemo()
the actions block to optimize it and make it faster.