Reputation: 647
I was looking through the source code for useSelector
as part of the react-redux library.
I was wondering if useSelector
automatically unsubscribes components from redux store updates when the component unmounts, similar to using the unsubscribe
function returned by calling store.subscribe
in Redux? Or if another component changes that piece of state, will this still be subscribed to such changes?
Upvotes: 1
Views: 1126
Reputation: 67469
Yes, useSelector
explicitly unsubscribes from the store when the component unmounts. Per https://github.com/reduxjs/react-redux/blob/v7.2.2/src/hooks/useSelector.js#L81 :
useIsomorphicLayoutEffect(() => {
function checkForUpdates() {
try {
const newSelectedState = latestSelector.current(store.getState())
if (equalityFn(newSelectedState, latestSelectedState.current)) {
return
}
latestSelectedState.current = newSelectedState
} catch (err) {
// we ignore all errors here, since when the component
// is re-rendered, the selectors are called again, and
// will throw again, if neither props nor store state
// changed
latestSubscriptionCallbackError.current = err
}
forceRender()
}
subscription.onStateChange = checkForUpdates
subscription.trySubscribe()
checkForUpdates()
return () => subscription.tryUnsubscribe() // unsubscribes here
}, [store, subscription])
Upvotes: 4