Search code examples
design-patternsreactjsflux

Should component writes into store in React js app?


Is it a good idea, or is it an anti pattern, to allow direct writing into store from a React component? (without using dispatcher)


Solution

    1. Component should have single responsibility (one of the SOLID principles) - to render UI view. If it writes to the store, this principle is violated.

    2. To gain more reusability of components - it would be better to remove unnecessary dependencies. It case of direct writing to store your UI component will be dependent on the store implementation. Even better - remove dependency from dispatcher. Set callback explicitly with props:

      const Component = React.createClass({
        render: function() {
          return <button onClick={ this.props.onClick }></button>;
        }
      });
      
      <Component onClick={ callDispatcher } />
      

      In that case your Component is the most reusable. You can use it even in the different project with different 'flux' implementation.

    See many good ideas in Redux - it removes as many dependencies as possible from components. In Redux you have all your components "dumb" / "pure" (they haven't state) and you can attach state to component via function that take component by arguments (for example, Redux's connect). It also called higher-order component.

    A higher-order component is just a function that takes an existing component and returns another component that wraps it.

    See more details (from Redux author Dan Abramov).