A new way to implement Redux-like global store with React Hooks and React Context
In this article, I'm going to introduce a new way to implement a global store step by step by using React Hooks and React Context. The example code is available in GitHub.
1. Initialize the project
Let's create the project and install the dependencies.
npx create-react-app react-context-hooks
yarn install
yarn start
2. Local store(state)
Let's illustrate React local store in a simple counter example. There is a local state to manage the count variable, and a method - setCount to update it. It's quite straight forward, however it's restricted within the component to update count. What if we need to update from other components? React provides Context to achieve that.
3. Global store(state)
First of all, you need to walk through a basic tutorial for React Context. In a nutshell, React Context provides a way to pass data through the component tree without having to pass props down manually at every level.
3.1 ContextProvider
We define a count state and pass the value to the global context so that its descendants can access count and setCount. As you can see, we use React hooks API: useContext. If you’re familiar with the context API before Hooks, useContext(CounterContext)
is equivalent to static contextType = CounterContext
in a class, or to <CounterContext.Consumer>
. We also create a provider for its descendants to consume and subscribe to changes.
3.2 Consume Context
We'll create two components called counterview and countercontroller to display and update the count variable in global store, which will leverage useCounterStore function.
CounterView:
CounterController:
main app:
We just need render CounterView and CounterController as the children of CounterProvider so that they can consume the Context.
4.Further example: userReducer
In this chapter, we will move forward to a more complicated example in which React Context works together with useReducer API to achieve Redux-like global store. If you are not familiar with Redux, please check my article - https://dzone.com/articles/how-to-build-a-single-page-ui-application-by-using.
4.1 Actions
We define two actions to manipulate the global store: increase and decrease
4.2 Reducers
I prefer to use the generic way to define reducers, but you also can see the commented code below which is more direct.
4.3 global store: useReducer together with React Context
As you can see from the code, the only difference to chapter 3 is to bind useReducer to the context provider. So it would be straight forward to understand the code.
4.4 Access to global store and dispatch actions
There is a slight difference to chapter 3. We can access the state and dispatch by using useCounterStore,
CounterView:
CounterController:
Comments
Post a Comment