When state variables depend on each other, it's important to use the functional form of the state updater function to ensure that you are working with the most recent state. This is especially important in cases where one state update relies on the value of another state.
Here's an example:
import React from 'react';
const MyComponent = () => {
const [count, setCount] = React.useState(0);
const [doubleCount, setDoubleCount] = React.useState(0);
const updateCounts = () => {
setCount(prevCount => prevCount + 1); // Update count based on previous value
setDoubleCount(prevCount => (prevCount + 1) * 2); // Update doubleCount based on previous value
};
React.useEffect(() => {
setDoubleCount(count * 2); // Update doubleCount whenever count changes
}, [count]);
return (
<div>
<p>Count: {count}</p>
<p>Double Count: {doubleCount}</p>
<button onClick={updateCounts}>Increment Count</button>
</div>
);
};
export default MyComponent;
In this example:
- The
countstate is updated using its previous value. - The
doubleCountstate is updated in auseEffecthook that runs whenevercountchanges, ensuring thatdoubleCountalways reflects twice the value ofcount.
This approach helps maintain consistency between the dependent states.
