Skip to content

Instantly share code, notes, and snippets.

@gaearon
Created November 1, 2018 10:05
Show Gist options
  • Save gaearon/cb5add26336003ed8c0004c4ba820eae to your computer and use it in GitHub Desktop.
Save gaearon/cb5add26336003ed8c0004c4ba820eae to your computer and use it in GitHub Desktop.
Examples from "Making Sense of React Hooks"
function MyResponsiveComponent() {
const width = useWindowWidth(); // Our custom Hook
return (
<p>Window width is {width}</p>
);
}
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
});
return width;
}
@earthtosid
Copy link

How would one go about testing these event listeners?

Copy link

ghost commented Dec 6, 2019

Hi @gaearon, I'm very new to hooks, but isn't this typically the case where you would opt out from cleaning at each render in useEffect and rather have:

useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []); // <-- empty array

As suggested in the note from the docs, the empty array makes it so that the effect is run and cleaned up when the component mounts / unmounts.

Otherwise you would add and remove a window listener at each render, right?

I had same thought, I wonder why Dan uses his original example though (useEffect without []) - it can be slightly confusing. @gaearon

@cs-joy
Copy link

cs-joy commented Sep 26, 2021

i am one of the newbie in react learning.
thank you for explanation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment