I don't understand how does my component Word will rerender. I have a redux state keeping my {history: {letters}} state. So the question is: If {letters} are passed into useEffect deps array, will my component Word rerender if {words} property is changed?
`
function Word() {
const { history: {letters, words} } = useAppSelector(state => state)
useEffect(() => {
}, [letters])
return (
<div>
</div>
)
}
`
I expect my component rerender only if letters are changed.
CodePudding user response:
You are maintaining a state using Redux. So, the component re-renders if any state used in the component itself is changed. In your case, your Word
component will re-render if letters
or words
or both got changed. That's how it works.
BTW, your useEffect
should only be triggered upon any change in letters
only since you have included only letters
in its dependency array.
If you want to optimize the performance, you can memorize things using useMemo
and useCallback
wherever necessary. Pass the dependencies correctly to recalculate them only upon required state changes.
CodePudding user response:
UseSelector will already rerender if the selected part of the state has change. you dont have to add [letters]
on useEffect
UseSelector is subscribed to the state and if detects any change, it calls checkForUpdates
subscription.onStateChange = checkForUpdates
and checkForUpdates
checks if the reference of the state changed, if it did. it calls forceRender
function so your component renders.
useEffect
is used to dispatch actions to populate the state before the component first renders so useSelector will have access to newly populated the state