Reputation: 630
The following React component is rendered every 50ms. The value of s
increases by 1 every second. When it does, I'd like to add the value of word
to an array in state.
When the code runs, the word
gets added to the array as intended. Then React does its second Strict Mode render of the entire app end everything looks the same.
On next iterations however, when s
increases, the second pass only results in a different behavior and nothing gets added to the array beyond that.
export const Component = ({ word, s }) => {
const lastS = useRef()
const [words, setWords] = useState()
if (s !== lastS.current) {
console.log('adding', word, words, s, lastS.current)
setWords([...words, word])
lastS.current = s
}
console.log('rendered', word, words, s, lastS.current)
}
Console output when s
changes for the first time is what I expect:
1st pass : adding apple > Array[] 9 undefined // inside "if" statement
1st pass : rendered apple > Array[] 9 9 // component renders
1st pass : rendered apple > Array["apple"] 9 9 // state changed, rerender
2st pass : adding apple > Array[] 9 undefined // same as 1st
2st pass : rendered apple > Array[] 9 9 // same as 1st
2st pass : rendered apple > Array["apple"] 9 9 // same as 1st
However, the next time s
changes I get the following output. The second pass doesn't add word
to the array.
1st pass : adding orange > Array["apple"] 10 9
1st pass : rendered orange > Array["apple] 10 10
1st pass : rendered orange > Array["apple", "orange"] 10 10
2st pass : rendered orange > Array["apple"] 10 10 <------------ why?
Why are the two results different? What is the side effect here?
Upvotes: 1
Views: 91