This is a workaround when State cannot be handled correctly in the event listener of the function component.
When you try to reference the state of React.useState () in the event listener's callback function, the value may not be up to date.
State called counter+ 1 to counterfunc ()counterFunction component
// ①
const [counter, setCounter] = React.useState(0);
// ④
const func = () => {
console.log(counter);
};
// ③
React.useEffect(() => {
window.addEventListener("click", func);
}, []);
// ②
return (
<button onClick={() => setCounter(counter + 1)}>
button
</button>
** In this example, the value output by ④ console.log (counter) is always 0. ** **
It is fixed at the value of counter at the time of registration of the event listener, and the output does not change even if the state is updated.
I don't know how many times I clicked on it ...
You can always refer to the latest status by using React.useRef ().
Examples that work
const [counter, setCounter] = React.useState(0);
//add to
const counterRef = useRef(); //Create ref object
counterRef.current = counter; //ref refers to counter
const func = () => {
//Output ref
console.log(counterRef.current);
};
// -----The following is unchanged-----
React.useEffect(() => {
window.addEventListener("click", func);
}, []);
return (
<button onClick={() => setCounter(counter + 1)}>
button
</button>
Instead of using counter in the callback, use counterRef.current.
By doing this, you can refer to the latest state.
If the latest state is not visible in the function component's event listener, use Ref to reference State instead of using State in the callback.
By doing this, you can refer to the latest state.