score:0

Accepted answer

this is tricky but trivial for lots of projects. your useeffect will be trigged one time and the function inside will be trigged everytime the user resize the browser.

sometimes when you resize the browser you cannot access state or set the state (using usestate) so i like to put the value of the width of the window outside. this way i can reuse the values anytime with almost no conflicts.

// react using hooks
import { usestate, useeffect } from 'react';

// use outside the component
let ismobile = true; // variable to check width

const mycomponent = () => {

    // optional: save the width of the window using state
    const [width, setwidth] = usestate(window.innerwidth); // check width size of the window
    const handlewindowsizechange = () => {
        setwidth(window.innerwidth);
        ismobile = window.innerwidth < 700 ? true : false;
    };

    // call your useeffect
    useeffect(() => {
        window.addeventlistener('resize', handlewindowsizechange);
        return () => {
            window.removeeventlistener('resize', handlewindowsizechange);
        };
    }, []);

    // view of the component
    return (<h1>{ismobile}</h1>)

}

score:0

you want to use useeffect to add the event listener (and remove it).

const handleresize = () => {
   ...
}

react.useeffect(() => {
  window.addeventlistener('resize', handleresize)

  return () => window.removeeventlistener('resize', handleresize)
}, [])

this will add the event listener when the component is rendered, and remove it when it's not (the return value of useeffect is run on cleanup). useeffect will run every time a variable in the array in the second parameter changes (in this case it's left as empty [], so it will only run once).

also, instead of using settimeout, you should consider using a "debounced" function, this post explains how they work. you can find debounce functions to reuse on npm and in lodash etc.

score:0

you should actually use uselayouteffect to handle this kind of computation, because it is triggered while the component renders (after the computation is done, but before the painting is done), as opposed to useeffect, that runs after the component has rendered.


Related Query

More Query from same tag