Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why to pass callbacks in React component's props instead of using react-redux's connect? [closed]

Tags:

reactjs

redux

Why is it common that callbacks (or redux's dispatch) is passed in component's props rather than always using react-redux connect function?

Dispatch (or function wrapped in dispatch) as prop:

// somewhere.js, calling Component in JSX with onButtonClick as props
<Component onButtonClick={someFunction}/>

// component.js
const Component = ({onButtonClick}) => <Button onClick={onButtonClick}>{'do something'}</Button>

vs.

Connect function:

// somewhere.js, calling Component in JSX without giving props
<Component/>

// component.js
const Component = ({onButtonClick}) => <Button onClick={onButtonClick}>{'do something'}</Button>
const mapDispathToProps = (dispatch, ownProps) => {
   return {
            onButtonClick: dispatch(someFunction)
          }
}
connect(mapDispathToProps)(Component)
like image 326
Lalli Nuorteva Avatar asked Oct 19 '22 14:10

Lalli Nuorteva


1 Answers

The difference is "presentational" and "container" components, also called smart and dumb components previously. The container component is the one that you "connect" and the presentation component is the one that just receives props.

I'll link out to this Medium article by Dan Abramov, the creator of redux.

To quote out the benefits section:

  • Better separation of concerns. You understand your app and your UI better by writing components this way.
  • Better reusability. You can use the same presentational component with completely different state sources, and turn those into separate container components that can be further reused.
  • Presentational components are essentially your app’s “palette”. You can put them on a single page and let the designer tweak all their variations without touching the app’s logic. You can run screenshot regression tests on that page.
  • This forces you to extract “layout components” such as Sidebar, Page, ContextMenu and use this.props.children instead of duplicating the same markup and layout in several container components.

In my personal experience, forcing myself to use this style does keep my components more "sane" and easier to understand/maintain. You are welcome to not use this style, but when you run into issues you might need to refactor to use this method that better separates concerns.

If I were to summarize without Dan's help, I'd say this: connecting all over the place makes it confusing as to where each prop that you have in your component comes from. If you force yourself to only connect at very specific places (in my projects, I tend to connect at the page level, and the root level), then you'll always know where things come from which helps debugging when things go wrong.

like image 72
Ted Morin Avatar answered Oct 21 '22 04:10

Ted Morin