1

I am diving into Redux toolkit and made a simple project to understand its concepts better.

function App() {
 //..
 return(
  <UserList /> // uses submittedUserSelector
  <UserInformation /> // uses selectedUserSelector
 );
}

The basic idea is that you can either add a user to UserList or select one from the list which will be shown in UserInformation. Both the submitted and selected user are managed by different reducers in the same store.

export const rootReducer = combineReducers({
    form: formReducer, // have submitted user selector
    user: userReducer // have selected user selector
});

// formReducer.tsx
 export const submittedUserSelector = (state:RootState)=>state.form.submittedUser; //object
// selectedUserReducer.tsx
 export const selectedUserSelector = (state:RootState)=>state.user.selectedUser; //object

According to the official documentation and I quote:

When an action is dispatched, useSelector() will do a reference comparison of the previous selector result value and the current result value. If they are different, the component will be forced to re-render. If they are the same, the component will not re-render.

So I was expecting that when I selected a user which dispatches an action in userReducer would result in re-rendering UserList as well (as submittedUserSelector returns an object). That didn't happen, however.

Why? Does redux-toolkit figure out which components in the tree are using a particular selector and only evaluate those? Is that somewhere in the documentation?

juanjo12x
  • 183
  • 1
  • 3
  • 15

1 Answers1

3

Selectors will be called on every state change and only cause a component rerender if the selector result changes from the last render - so usually, unrelated components will not be rerendered.

Keep in mind that general React component rendering still applies - if a parent component rerenders, all child components will be rerendered.

This has nothing to do with redux-toolkit though - it is the normal behaviour of the react-redux hooks. See https://react-redux.js.org/api/hooks

phry
  • 35,762
  • 5
  • 67
  • 81