Sometimes i was opportune to work with react legacy projects and in the cause of debugging, i had come across code that i felt is not safe. I would like to share with you the convenient and safer way to manipulate state in React Hooks which is “Previous state”. Before we delve into updating and using previous state, let’s recap about state first. In my previous post, i wrote about state for class based component and functional based component and used only one method to manipulate state. I defined state as an object which allows us to manage data dynamically within the component. In other words, state is mutable data in React component. However, I found that there are many ways to manipulate state and the idea of previous state is what we will be discussing here.
In this post, we will look at how to set state base on the previous state value. In the example here, we are going to be implementing a counter. But this counter will have buttons to increment, decrement, and reset the count value. The image below depicts the first example.
First, we created a counter functional component, next we used the useState Hook to create a state variable and the corresponding setter function. In the JSX, we added the three buttons to increment, decrement and reset the count value. For the increment button, onclick is an arrow function, call setCount passing in initialCount + 1 as the argument. For the decrement button, onclick is similarly an arrow function, call setCount and passing in initialCount — 1 as the argument and for the reset button, onclick is an arrow function, call setCount and passing in initialCount as the argument which is going to set the count value back to zero. When you click on the increment button, decrement button and reset, it pretty worked. The current implementation and the way we incremented the count value is not safe. Although it looks like it is working but it’s not the right way to change the count value. The convenient and safer way to change the count value is using previous state.
To overcome this, we need to pass in a function that has access to the old state value as depicted in the image below.
So setCount accepts a function that has access to the old count. So prevCount is the argument and the function body prevCount + 1. We pass in a function that has access to the old value and increment that by one. Anytime you need to update the state value based on the previous state value, always go with the safer option of passing in a function that will set the new state value. Let me show the class based component equivalent as depicted below.
NOTE: When you have to update state based on the previous state value, pass in a function to the state setter.
Thank you all for reading this post. Give me a clap for this post.