Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add DOM elements to my state, with useEffect hook without error/warning in the console?

I'm actually trying to target some DOM elements in my empty state with useState and useEffect hooks.
No problem at all, I think I'm doing right. Here's my actual code :

const [state, setState] = useState({
    title: [],
    subtitle: []
});

useEffect(() => {
    const myNewTitle = ["Hello", "World"];
    const myNewSubtitle = ["What's", "up?"];

    setState({...state, title: myNewTitle, subtitle: myNewSubtitle})
    console.log(state)
}, [state]);

Here, my console displays an infinite loop.
I tried to write an empty array [], but the new values of my state are not displaying in the console, like I would like to.
So, I wrote this : [state.title[0], state.subtitle[0]]);

I don't know if my code is correct or not. The console displays what I wanted, the new values of my state.
But I got this warning in my console :

React Hook useEffect has a missing dependency: 'state'. Either include it or remove the dependency array. You can also do a functional update 'setState(s => ...)' if you only need 'state' in the 'setState' call react-hooks/exhaustive-deps

Actually, I don't know how to fix this issue. Can someone help me, please ?

Precisions : Of course, this is a really easy example. In my project, I want to re-use my state (title+subtitle) in functions wrote outside of the useEffect hook.

like image 212
Lucie Bachman Avatar asked Oct 23 '25 15:10

Lucie Bachman


1 Answers

You can avoid having to put state in the dependency list by using the callback version of setState() which has the current state as a parameter.

Since that parameter is local (inside) the useEffect, it's not necessary to declare it as a dependency.

useEffect(() => {

  const myNewTitle = ["Hello", "World"];
  const myNewSubtitle = ["What's", "up?"];

  setState(oldState => {
    return {...oldState, title: myNewTitle, subtitle: myNewSubtitle};
  });

}, []);
like image 144
Richard Matsen Avatar answered Oct 26 '25 04:10

Richard Matsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!