Search code examples
reactjsreduxreact-reduxcode-reuse

How to re-use a component in React and Redux?


Maybe I didn't get the concepts right. I usually see in the examples, a Counter class and then the mapStateToProps and mapDispatchToProps, and then using connect to create the "Higher Order Component" and export it as the default.

I wonder how do we re-use this Counter component?

For example:

  1. If we need two instances of Counter on the same page
  2. If we need Counter on page 2, and it should be related to another redux state (not the one we defined in that original file)

And then it dawns on me: it seems in practice, we actually may just define Counter.js without all those mapStateToProps, mapDispatchToProps, and connect, and then we would create IceCreamCounter.js that first import Counter (the plain counter) and does all the mapStateToProps, mapDispatchToProps, and connect to make it into one HOC and export it?

And then if the same page need another counter, then we use mapStateToProps, mapDispatchToProps, and connect in, for example, DrinkCounter.js and do the appropriate mappings to the redux store.

Likewise, if it is the "To Go Order" page, and we need a counter for the number of spoons needed, then we actually would have mapStateToProps, mapDispatchToProps, and connect and create a SpoonCounter.js:

import { connect } from 'react-redux';

import Counter from './Counter';  // the plain counter component

const mapStateToProps = ...;
const mapDispatchToProps = ...;

const SpoonCounter = connect(mapStateToProps, mapDispatchToProps)(Counter);
export default SpoonCounter;

and that's how we achieve component re-use?

I wonder why I didn't see how this is done before... is it actually explained in some official docs or blogs?


Solution

  • Not an official doc, per se, but from a fairly "official" source. The container component pattern. This is the post that turned me on to the pattern.

    https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0

    Here you've stumbled upon it. The "dumb" counter component is the presentation component, the visual aspect, the UI, whereas, in your case, the react-redux connect HOC returns the "smart" component, it connects tangible data, like your app state, to the presentation component.