Mastering Usestate in React
Mastering Usestate in React
Mastering useState
in React:
A Beginner’s Guide
Slim toumi
Slim toumi
React js tips
What is useState ?
useState is a React hook that lets functional components manage state, a
feature that was previously exclusive to class components.
Using useState
To start using useState, import it at the top of your component:
Setting Up useState
Calling useState with an initial value creates state in a component. This
returns an array with two elements
Explanation :
count : starts with an initial value of 0.
setCount : is used to update count and re-render the component.
Slim toumi
Slim toumi
React js tips
Updating State
To change the state value, call the updater function, setCount. This
will schedule a re-render:
Note:
setCount does not immediately update the state. Instead, it schedules
an update, which is important if your updates depend on the previous
state.
Slim toumi
Slim toumi
React js tips
Note:
Using prev ensures that updates are accurate, especially when multiple
updates are triggered in rapid succession.
Note:
Each piece of state has its own variable and updater, keeping your code
modular and clear.
Slim toumi
Slim toumi
React js tips
Example with an Object: Let’s say you have a state variable holding
an object with user details, and you want to update just one part of it.
Explanation :
...prevUser copies all properties from the previous user state.
name: 'John' updates the name while keeping the rest unchanged.
Note:
Why this is important: Directly modifying state can cause unexpected
behavior because React may not detect the change. Always return a
new object or array to let React know there’s an update.
Slim toumi
Slim toumi
React js tips
Slim toumi
Slim toumi