Master React Unidirectional Data Flow
Tags: react, dataflow, unidirectional
Published: 2021-05-22 04:06:57

<!-- wp:paragraph -->
<p>As with any form of programming, there are dozens of ways to manage data inside a React application. That said, not all methods are equally capable of scaling. There are some "suggested patterns" for your React applications to follow that will ensure you're not forced to pause in order to reorganize or re-evaluate your existing code when you’re building the application.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Today, we'll be covering one of the most important structural best practices to follow when building your React applications: Unidirectional data flow.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>What is Unidirectional Data Flow?</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Unidirectional data flow is the idea that components should only receiveraise data in one direction. Child components should only call functions from parent components, while parent components should only set/pass data to their children.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":1501,"sizeSlug":"large","linkDestination":"media"} -->
<figure class="wp-block-image size-large"><a href="https://coderpad.io/wp-content/uploads/2021/04/img_6088a07a0be12.png"><img src="https://coderpad.io/wp-content/uploads/2021/04/img_6088a07a0be12-1024x534.png" alt="A graph showing unidirectional data flow being good but bidirectionality being bad" class="wp-image-1501"/></a></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>In order to explain how both of these look in real code, let's start with how a properly unidirectional parent and child component would be written.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Unidirectional Demo</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>A great example of a set of components we'll use to demonstrate unidirectionality is a parent "App" component and a child "Form" component.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's take a look at a code sample that follows this unidirectionality first:</p>
<!-- /wp:paragraph -->

[View the code sample on CoderPad](https://app.coderpad.io/sandbox?question_id=176771)

<!-- wp:paragraph -->
<p>As you can see we're passing the onChange and value props to SimpleForm. This keeps our state consolidated inside of the App component rather than split between App and SimpleForm. Once you "submit" the form, SimpleForm calls onDone which changes the state stored inside of App. This in turn causes a re-render of SimpleForm.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>While SimpleForm is displaying the data to the user, the logic itself stays within App. SimpleForm contains no state or application logic; we call components like these "dumb" components. "Dumb" components are utilized for styling and composability, but not for app logic or state.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This is what a set of proper React components <em>should</em> look like. This pattern of raising state out of the component itself and leaving "dumb" component comes from the guidance of the React team itself. This pattern is called<a href="https://reactjs.org/docs/lifting-state-up.html"> "lifting state up"</a>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now that we have a better understanding of the patterns to follow let's take a look at the wrong way to do things.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Breaking from Suggested Patterns</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Now that we've "lifted" the state, let's drop back down into SimpleForm. We'll start by changing SimpleForm to a class component and adding state.</p>
<!-- /wp:paragraph -->

```jsx
class SimpleForm extends React.Component {
// State is now a part of the SimpleForm component
  state = {
    input: ""
  }

  onChange(e) {
    this.setState({
      input: e.target.value
    })
  }

  render() {
    return (
      <div>
        <label>
          <div>Username</div>
          <input onChange={this.onChange.bind(this)} value={this.state.input}/>
        </label>
        <button onClick={this.props.onDone}>Submit</button>
      </div>
    )
  }
}
```

<!-- wp:paragraph -->
<p>Now, we can use ref in App to access the class methods and state.</p>
<!-- /wp:paragraph -->

```jsx
export default function App() {
  const simpleRef = React.useRef()
  const [displayTxt, setDisplayTxt] = React.useState("")

  const onDone = () => {
    // Reach into the Ref to access the state of the component instance
    setDisplayTxt(simpleRef.current.state.input)
  }

  return (
    <div>
      <SimpleForm
        onDone={onDone}
        ref={simpleRef}
      />
      <p>{displayTxt}</p>
    </div>
  )
}
```


[View the code sample on CoderPad](https://app.coderpad.io/sandbox?question_id=176773)

<!-- wp:paragraph -->
<p>This code works, but has some inherent complexity issues. When you start expanding this component, this idea of separating your state and having to inspect the child reference from the parent makes development more difficult. Let's take a look visually how following the application logic is now more difficult with this pattern.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Visualizing the Problem</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>First, let's start by taking a look at the simpleRef component, where the state is "lowered down" to the SimpleForm component:</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":1502,"sizeSlug":"large","linkDestination":"media"} -->
<figure class="wp-block-image size-large"><a href="https://coderpad.io/wp-content/uploads/2021/04/img_6088a07cc6cf6.png"><img src="https://coderpad.io/wp-content/uploads/2021/04/img_6088a07cc6cf6-1024x727.png" alt="A complex graph explained more below" class="wp-image-1502"/></a></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>In this example, the flow of the application state is as follows:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>App (and its children, SimpleForm) render</li><li>The user makes changes to the data stored in SimpleForm</li><li>The user triggers the onDone action, which triggers a function in App</li><li>The App onDone method inspects the data from SimpleForm</li><li>Once the data is returned to App, it changes its own data, thus triggering a re-render of App and SimpleForm both</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>As you can see from the chart above and the outline of the data flow, one action goes back and forth between the parent and child as App attempts to access the data stored in SimpleForm. This is a prime example of a bi-directional component action. This code sample gets even more complex when onDone is expected to change the state in SimpleForm.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now, let's contrast that to the mental model needed to work with unidirectionality enforced.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":1503,"sizeSlug":"large","linkDestination":"media"} -->
<figure class="wp-block-image size-large"><a href="https://coderpad.io/wp-content/uploads/2021/04/img_6088a07e1f014.png"><img src="https://coderpad.io/wp-content/uploads/2021/04/img_6088a07e1f014-1024x727.png" alt="A complex graph explained more below" class="wp-image-1503"/></a></figure>
<!-- /wp:image -->

<!-- wp:list -->
<ul><li>App (and its children, SimpleForm) render</li><li>The user makes changes in SimpleForm, the state is raised up to App through callbacks</li><li>The user triggers the onDone action, which triggers a function in App</li><li>The App onDone method already contains all of the data it needs in it's own component, so it simply re-renders App and SimpleForm without any additional logic overhead</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>As you can see, while the number of steps is similar between these methods (but may not be in a less trivial example), the unidirectional flow is much more streamlined and easier to follow.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This is why the React core team (and the community at large) strongly suggests you use unidirectionality as often as possible.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Conclusion &amp; Challenge</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Understanding React unidirectional data flow is integral to scaffolding scalable applications. Unidirectionality doesn't just apply to React, either - Angular and Vue applications often require similar patterns for large scale codebases to be easier to follow and more performant.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now that we have a deeper understanding of React unidirectional data flow, here's a challenge for you: Refactor the following components to better reflect unidirectionality in this coding pad.</p>
<!-- /wp:paragraph -->


[View the code sample on CoderPad](https://app.coderpad.io/sandbox?question_id=176774)

<!-- wp:paragraph -->
<p>The functionality of the app should be consistent with the previous version. Stuck?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Start with:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Move the getNewActivity into a React.useEffect in App</li><li>Move the state.activity into a React.useState in App</li><li>Pass all props to DisplayActivities, making it a "dumb" component</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Still stuck? Maybe you're excited to share your solution?<a href="https://twitter.com/CoderPad"> Send us a Tweet @CoderPad</a> or<a href="https://bit.ly/coderpad-slack"> ask us in our community Slack</a>. We'd be excited to hear from you!</p>
<!-- /wp:paragraph -->