In my component I'm setting up an event listener within the useEffect hook:
useEffect(() => {
const target = subtitleEl.current;
target.addEventListener("click", () => {
console.log("click");
onSubtitleClick();
});
return () => {
target.removeEventListener("click", null);
};
}, []);
.. but when I call onSubtitleClick, my state is stale - it's the original value. Example code here. How can I access state from the event handler that was setup with the useEffect?
Your event listener registers a function (reference) which has count as 0 in the environment it is defined and when a new render happens, your reference is not being updated which is registered with that element and that registered function reference still knows that count is 0 even though count has been changed but that updated function was not registered which knows the updated value in its context. So you need to update event listener with new function reference.
useEffect(() => {
const target = subtitleEl.current;
target.addEventListener("click", onSubtitleClick);
return () => {
console.log("removeEventListener");
target.removeEventListener("click", onSubtitleClick);
};
}, [onSubtitleClick]);
However, you don't need that messy code to achieve what you are doing now or similar stuff. You can simply call that passed function on click and don't attach to element through ref but directly in jsx.
<div
className="panelText"
style={{ fontSize: "13px" }}
onClick={onSubtitleClick}
ref={subtitleEl}
>
Button2
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With