1
votes

I'm learning React Hooks, and I'm actually using the useEffect method. No problem at all, but I got some warnings about my variable declarations. Here's an example of what I wrote :

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

function App(){
  let containerRef = useRef(null);

  let myVariable;

  useEffect(){
    myVariable = containerRef.children[0];
  }

  return(
    <div className="container" ref={el => containerRef = el}>
        <h1>Hey, I'm Laurie </h1>
        <p> Nice to e-meet you!</p>
    </div>
  )
}

This is just an easy and uncompleted example of what I did, for animating my website with GSAP. I access to the DOM elements with useRef and I only found this solution. But my console write me some warnings, and I'm pretty lost.

Warning I got :

Assignments to the myVariable 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.

Can someone help me with this issue ?

1
This snippet is not a valid javascript, also, the warning explains the problem well, what kind of answer are you looking for? How to approach the problem better?Dennis Vash

1 Answers

7
votes

when you are using Hook basically you are telling React that your component needs to do something after render. React will remember the function you passed, and call it later after performing the DOM updates.

More Details

https://reactjs.org/docs/hooks-effect.html#example-using-hooks

Regarding warning: React doesn't remember your myVariable. It will be recreated on each render. It will be better to use useState hook to set value in useEffect and remember it on the next render.

Remember one thing always pass the second argument in useEffect with an array of dependencies.