showing results for - "react responsive screen size"
Elisa
09 Nov 2016
1const MyComponent = () => {
2  // Declare a new state variable with the "useState" Hook
3  const [width, setWidth] = React.useState(window.innerWidth);
4  const breakpoint = 620;
5
6  React.useEffect(() => {
7    /* Inside of a "useEffect" hook add an event listener that updates
8       the "width" state variable when the window size changes */
9    window.addEventListener("resize", () => setWidth(window.innerWidth));
10
11    /* passing an empty array as the dependencies of the effect will cause this
12       effect to only run when the component mounts, and not each time it updates.
13       We only want the listener to be added once */
14  }, []);
15
16  return width < breakpoint ? <MobileComponent /> : <DesktopComponent />;
17}