Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can not get clientWidth using useEffect

I want to get windowsize of the browser and according to this condition I want to render something in the component.
When I try to get clientWidth using useEffect, I get the value. However, I can not assign it the variable which I defined it in useState.

This is my code. and sometimes I’m getting the following error which I don’t understand because I don’t assign anything to constant variable. I try to assign variable of useState.

import React, { useState, useEffect } from 'react';

export default function App() {
  const [isMobile, setIsMobile] = useState(false);

  useEffect(() => {
    if (document.documentElement.clientWidth <= 400) {
      console.log(document.documentElement.clientWidth);
      setIsMobile = true;
    }
  }, []);

  return (
    <div>
      {(() => {
        console.log(isMobile);
        if (isMobile === true) {
          return <div>This is Mobile</div>;
        } else {
          return <div>This is normal</div>;
        }
      })()}
    </div>
  );
}

And this is the written version in stackblitz.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

https://stackblitz.com/edit/react-i9ewp6?file=src/App.js

>Solution :

You are trying to assign a value to the setIsMobile state updater function, which is declared const, so you can’t reassign a value to it anyway. You need to call the function with the value you want to update state to.

useEffect(() => {
  if (document.documentElement.clientWidth <= 400) {
    console.log(document.documentElement.clientWidth);
    setIsMobile(true);
  }
}, []);

or more succinctly

useEffect(() => {
  setIsMobile(document.documentElement.clientWidth <= 400);
}, []);

Since isMobile is a boolean value, it’s considered anti-pattern to compare it against true|false, just use its "boolean-ness" directly.

return (
  <div>
    {isMobile ? (
      <div>This is Mobile</div>
    ) : (
      <div>This is normal</div>
    )}
  </div>
);

Also, if you want to log values do it in an useEffect hook as an intentional side-effect.

useEffect(() => {
  console.log(isMobile);
}, [isMobile]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading