The basics of Hooks
If you are already familiar with React Hooks, you can skip this part.
Before Hooks, functional components had no state. Now, with the
useState(), we can do it.
It works by returning an array. The first item of the above array is a variable that gives access to the state value. The second item is a function that updates the state of the component to reflect the new values on the DOM.
Class components manage side effects using life cycle methods, like
useEffect() function lets you perform side effects in function components.
By default, effects run after every completed render. But, you can choose to fire it only when certain values have changed, passing an array of variables as a second optional parameter.
To have the same result as
componentDidMount() we can send an empty array. Knowing that an empty set does never change, the effect will run only once.
We can see that Hooks states works exactly like class component states. Every instance of the component has its own state.
To work a solution which shares state between components, we will create a custom Hook.
The idea is to create an array of listeners and only one state object. Every time that one component changes the state, all subscribed components get their
setState() functions fired and get updated.
We can do that by calling
useState() inside our custom Hook. But, instead returning the
setState() function, we add it to an array of listeners and return a function which updates the state object and run all listeners functions.
Wait. Isn’t this supposed to make my life easier?
Yes. I created a NPM package which encapsulates all this logic.
You will not need to this rewrite this custom hook on every project. If you just want to skip ahead and use the final solution, you can easily add it in your project by running:
npm install -s use-global-hook
You can learn how to use it by the examples in the package documentation. But, from now on, we are going to focus in how it works under the hood.
The first version
To use it on a component:
This first version already works sharing state. You can add as many Counter components as you want in your application and it will all have the same global state.
But we can do better
What I didn’t like in this first version:
- I want to remove the listener from the array when the component is unmounted.
- I want to make it more generic, so we can use in other projects.
- I want set a
- I want to use more functional oriented programming.
Calling a function just before component unmount
We learned that calling the
useEffect(function,), with an empty array, has the same use as
componentDidMount(). But, if the function used in the first parameter returns another function, this second function will be fired just before the component is unmounted. Exactly like
This is the perfect place to remove the component from the listeners array.
The second version
Besides this last modification, we are also going to:
- Set React as a parameter, not importing it anymore.
- Not exporting the customHook but, exporting a function that returns a new customHook according to
- Create a
storeobject that contains the
statevalue and the
- Replace the arrow functions for regular functions in
useCustom(), so we can have a context to bind the
Because we have a more generic Hook now, we have to setup it in a store file.
Separating actions from components
If you ever worked with complex state management library, you know that it is not the best idea to manipulate global state directly from the components.
The best way is to separate the business logic by creating actions which manipulate the state. For that reason I want that the last version of our solution doesn’t give component access to the
setState() function, but a set of actions.
To work that out, our
useGlobalHook(React, initialState, actions) function will receive an
action object as a third parameter. Regarding that, there are somethings that I want to add:
- Actions will have access to the
storeobject. For that reason, actions may read the state with
store.state, write state through
store.setState()and even call other actions using
- For organization, the actions object may contain other actions’ sub-objects. So, you may have an
actions.addToCounter(amount)or a sub-object with all counter actions called with
The final version
The following file is the actual file in the NPM package
Examples of use
You will never need to touch the
useGlobalHook.js again. You may focus now on your application. Here are two examples of how to use it in real life.
Several counters, one value
Add as many counters as you want, it will all share the same global value. Every time one counter add 1 to the global value, all counters will render. The parent component won’t need to render again.
Asynchronous ajax requests
Search GitHub repositories by username. Handle the ajax request asynchronously with async/await. Update the requests counter on every search.
And there we have it!
Our very own state management library with React Hooks!
Update — September 2019
On version 0.1.10 we add a important feature to the library. Now we can map a subset of the global state before use it. This will avoid unnecessary renders on every global state change.
On the following example, we have 2 counters on global state: counterA and counterB. As you add values to the counterA, the counterB component will not re-render and vice versa.
Try the button Add 10.000 CounterB components. It will make update the value of counterB very slow, but update counterA will continue fast.