useState():
- It is used for state management.
- It is used to store some values.
- We can store either primitives, arrays, or objects.
- The useState hook contains two arguments: the first argument takes the value, and the second argument is a function.
- useState() hook contains two arguments it is stored in the form of an array.
Key points :
- If the state is changing, then the entire component will be re-rendered.
- If the user refreshes the page, then the state is set to the default state(initial value).
- The state is not persistent.
- Use the useState hook to track a small amount of data. If you need to track a lot of data, you may want to consider using a different state management library.
- Use the useState hook to track data that changes over time. If the data does not change, you can use a constant instead.
- Use the useState hook to track data that is specific to the current component. If the data is shared between components, you may want to consider using a different state management library.
Note: If you declare a state variable with the let keyword, you are able to update the state variable directly, but it won’t trigger a re-render.
export default function Test() {
let [count, setCount] = useState(0);
useEffect(() => {
console.log("count1", count); //0
count++;
console.log("count2", count); //1
}, []);
return (
<div>
<h1>{count}</h1> //0
</div>
);
}
Note: If the component is re-rendered, the useState is invoked again, but this time it has its own updated state instead of the initializes with default state.
If you refresh the page, the state variables are set to the default state.