alrob
alrob

Reputation: 835

performance: connecting to the Redux store vs passing data through props

I'm using the redux store for all my major components, but for smaller components, I've just been passing down regular react props. Which is more efficient?

If have many smaller components, does it make any difference to pull from redux or pass down in regular props?

The Redux docs says:

many individual components should be connected to the store instead of just a few

This sounds like I should be connecting even my smaller (sometimes very tiny) components too. Currently, I am using the store in many, but not all, components.

Upvotes: 3

Views: 4242

Answers (1)

brietsparks
brietsparks

Reputation: 5006

connecting smaller components is more performant because when Redux state changes, only the affected components will rerender. Passing down regular React props is less efficient because when state changes, that change gets passed through many nested components down to the small component, causing all those components to rerender.

While connecting small components is more performant, it comes with some drawbacks described in this answer. To summarize, connecting a component couples it to the Redux state. So, the component must be tested with a store, and the component can't be modular unless store implementation goes with it. The solution to this is to separate a component's stateful logic from its stateless logic.

const StatefulTodo = ({ id }) => {
  const todo = useSelector(state => getTodo(state, {id});

  return <StatelessTodo {...todo} />
}
const StatelessTodo = ({ ...todo }) => {
  return (
    <div>
      <p>{todo.title}</p>
      <p>{todo.description}</p>
      ...etc
    </div>
  )
}

With this approach, a Todo UI can communicate application state while being decoupled from the state, testable in isolation, and reusable.

In practice, you should decide which components to connect given the tradeoffs. A perceivably performant app doesn't have to prevent every possible unneeded rerender. And you can always use the React devtools profiler to see which components need to be optimized.

Upvotes: 7

Related Questions