Manage State Easier With React Hooks
React hooks have allowed us to simplify how we write components, and has given us to create new ways to manage state in our applications. However, state management in class components had some advantages in accessing state as soon as it updated. This could be achieved by passing a function to ‘setState’ to access the updated value right after state was changed. This was helpful since when react updates asynchronously. We can achieve the same thing with hooks.
All we need is the ‘useState’ and ‘useEffect’ hooks to create a new hook that will give us the functionality we are looking for. Then we can use it anywhere in our project.
This hook is called ‘useStateWithCallback’. It allows us to pass in a function that will be executed as soon as the state is updated where we can do whatever else we would like with the information. This is helpful in situations where you need to updated value right away.
We can do the same thing with ‘useReducer’ in the hook call ‘useReducerWithCallback’. This is useful if you need to use the reduced state immediately.
What if we wanted a hook that mimicked ‘setState’ is almost every way? Where we could just create an object of our state and update it in the same way? Well, there is the ‘useSetStateWithCallback’ hook that we can use to accomplish this. This uses the ‘useReducer’ hook to give us the ‘setState’ ability we had with class components.
Hooks have allowed us to do some amazing things. Hopefully these three hooks will help you with any issues you have been facing with managing and updating state. Feel free to use these and edit them as you need.
If you liked this article, check out my other ones here.