useState lets your component “remember” things and update them when needed.
This could be:
useState
is a Hook that lets you add state to functional components. It returns an array with the current state and a function to update it.
import { useState } from 'react';
export default function MyApp() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<h1>Counters that update together</h1>
<MyButton count={count} onClick={handleClick} />
<MyButton count={count} onClick={handleClick} />
</div>
);
}
function MyButton({ count, onClick }) {
return (
<button onClick={onClick}>
Clicked {count} times
</button>
);
}
Using setCount(prev => prev + 1)
instead of setCount(count + 1)
is recommended in React in scenarios where the state update depends on the previous state. Here's why:
React batches state updates for performance optimization. If you use setCount(count + 1)
, the count
value might not reflect the latest state during the update process. This can lead to incorrect or stale values.
For example:
setCount(count + 1);
setCount(count + 1);