Home > other >  Assignments to the 'data' variable from inside React Hook useEffect will be lost after eac
Assignments to the 'data' variable from inside React Hook useEffect will be lost after eac

Time:08-14

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.

CodePudding user response:

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]);
  • Related