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.
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};
});
}, []);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With