How does useState() hook works(React Native Example)?

Mohita Prakash
Geek Culture
Published in
5 min readJan 9, 2022

People usually say “it’s all about getting the job done”. This line suits well for some of the budding software engineers who just want to impress the client or managers by delivering the task sooner than the expected time. In this situation, we focus only on the output rather than focusing on the proper implementation of concepts. In my view, working with software is like playing guitar or piano. You hit a few strings or press a key, you still get sound. Similarly, you write the code in a workaround manner or a tweaked way, the software still works. Then one day(mostly the demo day😁) that one uninvited guest shows up. None other than our lovely bug. Then we will be those clueless engineers who will become night owls and try to fix that bug at any cost. In this process, some people will invent their own patterns and anti-patterns and whatnot. This will thus go in a loop. To avoid all these dramatic side effects we just have to do one thing before writing any line of code — UNDERSTAND. Then it will be a beautiful journey and you will fall in love with coding.

React is a tricky but wonderful framework with which we can create magic once we understand it properly. After they introduced hooks, it has become more interesting as well. You have hooks for every problem or the confusion you faced while writing class components. Below I have tried to explain all the concepts about useState() hook which is the best of my knowledge. I have used a React Native application as a sample app to explain the logs. I hope you will enjoy the read…!!

Case:- 1 Behind the useState() hook

useState hook helps us to have state variables in function components. Thus the function components are not stateless anymore. Due to this reason, React suggests calling them “function components”. useState is a function that accepts the initial state as an argument and returns a state value and a function to update this value. This ensures that the React preserves the state between re-renders. The useState hook can be used to keep track of strings, numbers, booleans, arrays, objects, and any combination of these. Enough with the imagination right..?!! Let’s see this in reality. Try to execute the below code.

As we now know useState returns an array, we can use array destructuring to lessen the above code.

const [message, setMessage] = useState('Hello React')console.log(`State value is ${message}`)

So here variable message can be used to get the state value and setMessage can be used to update the state. In the next section, we will see what happens when we call setMessage() and try to update the state value.

Case:- 2 useState() is asynchronous

In the above code, we are taking an input message from the user, and on click of the ‘Save’ button, we are calling setMessage() to update the state value. Also, we are trying to access the state value just after calling the setMessage() function. Let’s analyze the logs.

Yes, You noticed it correctly..!!! React is not updating the state value immediately after the setMessage() function call. It enqueues this operation and after the component gets re-rendering the state value is updated with the most recent state value. Thus if we try to use the state value to store to DB or pass to some other function before component re-render then we will end up with the previous value. This explains the asynchronous behavior of useState even though it doesn’t return a Promise.

Case:- 3 Multiple calls to set State

In this section, we will see what happens when we call multiple setState together. Here on click of a button, I am calling 3 setState function calls to update the state value.

If you were expecting that the three setState will cause three times of re-rendering of the component, then you must continue reading the below lines. When setState function is called multiple times, React batches these calls and triggers re-render only once when the calling code is inside React-based event handlers. But if the setState is triggered asynchronously, React will not batch these multiple calls to setState instead each call will trigger a re-render. Try adding the below code inside handleButtonClickListener and check the logs.

setTimeout(()=>{setCount(val => val+1)setCountTen(val => val+1)setCountHund(val => val + 1)}, 1000)

Let’s try one more variation in this case. We will call the same state update function call multiple times and see the result. Add the below code to the handleButtonClickListener function and verify the logs. In this case also the React will batch these multiple calls and update the state value with the latest updated value(here count = 4).

const handleButtonClickListener = () => {console.log('Click Me Button Clicked')setCount(val => val+1)setCount(val => val+1)setCount(val => val+1)setCount(val => val+1)}

Case:- 4 Get the updated state value

What if we want to trigger some API call only after a state value has been updated. If we write this directly inside the render function, it will get called every time when the component gets re-render. For this, we can make use of useEffect hook with the state value as a dependency. Thus the useEffect will be triggered only when there is a change for the state value. You can execute the below code and verify the logs. After you click on the ‘Save’ button, the state value of message will be updated after the re-render. Also, the useEffect will get triggered. Then you click on the ‘Click Me’ button. Now you can see the component re-renders, but the useEffect isn’t getting triggered as there is no change for the state value of message.

useState makes the state management in a component very lean and simple. You can easily use it anywhere without a second thought once you understand its different behavior. I suggest all of you try the above examples, rather than just reading them for the purpose of a bug fix or a fresh start. By trying it out yourself, you can have a more in-depth understanding and you will never forget the concepts. By this article I believe, I could clear many of your guys' doubts on useState hook.

If you feel this article is helpful, please leave some claps and follow me so that it can reach all the needy. Also, it’ll be a great motivation for me to share more topics like this. #NeverStopLearning

--

--

Mohita Prakash
Geek Culture

Mobile Application Engineer | Talks about tech, finance and fitness | Believes in simplicity | Day Dreamer