So I have a parent component that maps an array of children and these children all have some state hook variable - in the example it's a string, but it could be anything.
When I filter the parent component array, the children mysteriously overtakes the state value from the former array: if the first child had set state to the string "true" - the first child in the NEW array also renders to "true".
I know/think it has to do with js references but I don't know how to fix it!
parent:
function App() {
const array = ['the', 'cat', 'and', 'the', 'old', 'hat']
const [words, setWords] = useState(array)
const filterWords = (e) => {
setWords(array.filter( a => a.includes(e.target.value)))
}
return (
<div className="App">
<input type='text' onChange={filterWords} />
{
words.map( word => <Sub word={word} />)
}
</div>
);
}
child:
const [state,
setState] = useState('false')
useEffect( () => console.log('rerendered', state) )
return (
<div>
<>{props.word}</>
<>{state}</>
<button onClick={() => setState('true')}>set state</button>
</div>
)
}
This renders a list that goes like:
the false [set state]
cat false [set state]
...etc
Now I click the first button so it goes
the true [set state]
cat false [set state]
...etc
Then I type the letter 'o' in the search box - now the app renders
old true [set state]
But the "old" child components state was never set to true right? I must be missing something fundamental, but I just don't get it.. Help much appreciated