Let’s fathom useState
Since the release of React Hook in 2019,
useState
is the most frequently used hook. It empowers frontend developers to create intricate UI/UX designs. However, we often take its functionality for granted until we stumble upon some serious issues while handling the state😥 such as accessing the state variable during updates, which is a common scenario when invoking search APIs based on real-time user input Therefore, in this discussion, I aim to shed some light on the mysterious behavior ofuseState
.
- Considering the simplest code snippet below, we invoke
alert()
by the click of a buttonUpdate Message
import "./styles.css";
import { useState } from "react";
export default function App() {
const [message, setMessage] = useState("Hello");
const handleClick = () => {
setMessage("Updated message");
alert(message); // Trying to access the state value immediately
};
return (
<div>
<p>{message}</p>
<button onClick={handleClick}>Update Message</button>
</div>
);
}
2. Based on the provided code and GIF, our expectation was for the alert
to display the Updated message
. However, when the button is clicked, it instead shows Hello
.
3. Nevertheless, we can update the alert
with the desired string "Updated message"
using useEffect
or directly feeding the string(i.e. "Updated message"
) into alert().
import "./styles.css";
import { useState, useEffect } from "react";
export default function App() {
const [message, setMessage] = useState("Hello");
useEffect(() => {
alert(message); // Accessing the updated state value in useEffect
}, [message]);
const handleClick = () => {
setMessage("Updated message");
// alert("Updated message"); //2nd approach to access the immediate value
};
return (
<div>
<p>{message}</p>
<button onClick={handleClick}>Update Message</button>
</div>
);
}
4. By incorporating the useEffect
in the above code, we have achieved depicting "Updated message"
within the alert
modal. But why doesn’t the previous code work? 🤔
5. It seems the useState
hook is asynchronous. Right? 🙄
6. Big No!🚫 Due to the batching technique of React, the value of message
has not been immediately updated, and the alert
has displayed the previous value of message
(i.e. Hello
)instead of the updated value (i.e. Updated message
).
7. So, In updated code, the useEffect
hook with a dependency on the message
ensures that the alert inside the useEffect
callback is invoked after the state update is complete and the message
value is up-to-date. Now, when we click the Updated message
button, the alert displays the updated value of the message
.
8. So, React’s batching is a technique that allows multiple state updates to be congregated and processed in a batch(group), rather than immediately triggering re-renders for each individual update. This batching process helps improve the performance and efficiency of React applications.
- When we trigger state update functions such as
setState
oruseState
setters multiple times within the same event handler, lifecycle method, or asynchronous callback, React combines those updates and applies them in a single render cycle. - This approach minimizes needless re-renders, enhancing performance. This operation occurs asynchronously, meaning that invoking
setState
oruseState
setters doesn't immediately trigger a state update and component re-render. - Instead, React enqueues the updates and processes them in a batch asynchronously, allowing for efficient optimization and scheduling of the updates. That’s why
useState
seems superficially as an async function but actually, it is 100% synchronous, meaning they are executed immediately and do not involve any asynchronous operations. - However, the rendering of the component itself, which may be triggered by state updates, is typically asynchronous. More deep insight.
9. Finally, we grasp why useState
works the way it works 🙏🏽.