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.