Skip to content

Instantly share code, notes, and snippets.

@wklsh
Last active October 9, 2020 17:25
Show Gist options
  • Save wklsh/1490c0395df2a5bcb844a49f6357c4e4 to your computer and use it in GitHub Desktop.
Save wklsh/1490c0395df2a5bcb844a49f6357c4e4 to your computer and use it in GitHub Desktop.
React eventListener + state handling

React event listeners with stale closure workaround

Component.jsx

function Component(props) {
  const [isFocused, setIsFocused] = useState(false);
  const mainComponentRef = useRef();

  useEffect(() => {
    // detect if clicks are occurring outside of cart content area. If it is, hide module
    const handleClickListener = ({ target }) => {
      if (isFocused && !mainComponentRef?.current?.contains(target)) {
        setIsFocused(false);
      }
    };

    if (isFocused && typeof document !== "undefined") {
      document.addEventListener("click", handleClickListener, { passive: true });
    }

    return () => {
      if (typeof document !== "undefined") {
        document.removeEventListener("click", handleClickListener);
      }
    };
  }, [isFocused]);

  return (
    <div ref={mainComponentRef} onClick={() => setIsFocused(true)}>
      // ...
    </div>
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment