Next.js Discord

Discord Forum

Update useState variable on first render

Unanswered
Yellowstripe scad posted this in #help-forum
Open in Discord
Yellowstripe scadOP
Hey there, I have this simple code

const [isMobile, setIsMobile] = useState(false) useEffect(()=>{ if (window.innerWidth <= 1024){ setIsMobile(true) } else{ setIsMobile(false)} },[isMobile])

It works when I change route, but on first load it doesn't update the isMobile variable when needed. Any help ?

7 Replies

Yellowstripe scadOP
Bump ?
Spectacled bear
What are you trying to achieve with this state management?
Looks like you are trying to change the UI based on the size of the window.

If that's the case you'd better change the CSS instead of the state/JS
Orangetailed potter wasp
What do you need the isMobile useState for?
if it's for rendering components or changing the styling of the components based on the screen size use media breakpoints
otherwise try adding window to the useEffect dependency array
The problem could be that somehow the useEffect is firing before window is defined. You can check this by console logging if window == null
In your current code, window.innerWidth will never update because you're not subscribing to updates. You can use the resize listener on the window object to check for changes.

import { useEffect } from 'react';
const MyComponent = () => {
  useEffect(() => {
    const handleResize = () => {
      // Perform actions on window resize
    };
    // Add an event listener to the window resize property
    window.addEventListener('resize', handleResize);
    return () => {
      // remove the listener when the component unmounts
      window.removeEventListener('resize', handleResize);
    };
  }, []);
  return <div>My Component</div>;
};

https://developer.mozilla.org/en-US/docs/Web/API/Window/resize_event

That said, if you're using isMobile to switch between styles for mobile devices, you're probably better off with CSS media queries to show or hide elements based on width

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries