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

Assignments to the 'data' variable from inside React Hook useEffect will be lost after each render

There is a complete warning message: Assignments to the ‘data’ variable from inside React Hook useEffect will be lost after each render. To preserve the value over time, store it in a useRef Hook and keep the mutable value in the ‘.current’ property. Otherwise, you can move this variable directly inside useEffect.

I am trying to use data state which is in the useState Hook in Material Table to display the data. That’s why i change const to let, But its keep giving me a warning and i dont know how to use useRef Hook with useState Hook.

const filterrr = () => {
    
    
            if (age.length !== 0) {
              return true;
            } 
            else {
              return false;
            }
        
          }
    
          let [data, setData] = useState(Data);
    
    
          useEffect(() => {
    
    
            console.log(Data);
            data = Data.filter(filterrr);
            setData(data);
          }, [age])

so i am trying to use useState outside the useEffect so other functions can use data state.

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

>Solution :

React useState() variables are immutable i.e. you cannot directly modify data just by declaring it with the let keyword. To clear this warning, modify your code as follows:

const filterrr = useCallback(() => {
  if (age.length !== 0) {
    return true;
  } else {
    return false;
  }
}, [age]);

const [data, setData] = useState(Data);

useEffect(() => {
  console.log("oldData", data);
  const newData = Data.filter(filterrr);
  console.log("newData", newData);
  setData(newData);
}, [filterrr]);

I have used useCallback() to wrap the filterrr() method so that we can add it to useEffect() dependencies array, this is a good practice in general.

If you don’t need filterrr() method elsewhere in your code, simply move it inside useEffect() without the useCallback():

useEffect(() => {
  const filterrr = () => {
    if (age.length !== 0) {
      return true;
    } else {
      return false;
    }
  };
  console.log("oldData", data);
  const newData = Data.filter(filterrr);
  console.log("newData", newData);
  setData(newData);
}, [age]);
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