Answer the question
In order to leave comments, you need to log in
How to get actual useState data in callback event?
It is necessary to listen to click on the entire page.
- You can use useRef inside the callback
- You can add state dependencies to useEffect, then each time it changes, the event handler will be removed and added.
How else can you do it?
import { useRef, useEffect, useState } from 'react';
export default function App() {
const [count, setCount] = useState(0);
const countRef = useRef();
countRef.current = count;
const clickEvent = () => {
console.log(`Count: ${count}; CountRef: ${countRef.current}`);
};
useEffect(() => {
document.addEventListener('click', clickEvent);
return () => {
document.removeEventListener('click', clickEvent);
};
}, [count]);
return (
<div>
<button onClick={() => setCount((n) => n + 1)}>Count: {count}</button>
</div>
);
}
Answer the question
In order to leave comments, you need to log in
I vote for useRef
import { useRef, useEffect, useState } from 'react';
export default function App() {
const [count, setCount] = useState(0);
const countRef = useRef();
countRef.current = count;
useEffect(() => {
const clickEvent = () => {
console.log(`CountRef: ${countRef.current}`);
};
document.addEventListener('click', clickEvent);
return () => {
document.removeEventListener('click', clickEvent);
};
}, [countRef]);
return (
<div>
<button onClick={() => setCount((n) => n + 1)}>Count: {count}</button>
</div>
);
}
useEffect(() => {
countRef.current = count;
}, [countRef, count]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question