Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access state from Event Handler created within React.js UseEffect Hook

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?

like image 593
GavinR Avatar asked Jun 24 '26 08:06

GavinR


1 Answers

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>
like image 193
Zohaib Ijaz Avatar answered Jun 27 '26 00:06

Zohaib Ijaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!