DEV Community

Timothy Fosteman
Timothy Fosteman

Posted on

Unidirectional Data Flow

Unidirectional Data Flow

React components communicate via props and have child-­parent relationships. Parent components can safely pass immutable data down to children. While children can push data up to parents via handlers (callbacks). A perfect flux-harmony
Flux Official Documentation

Background

If a component contains another component, it’s said to be the parent. A component within another component is said to be a child.

<Parent>
    <Child />
    <Child />
</Parent>
Enter fullscreen mode Exit fullscreen mode

Components that exist at the same level, such as two <Child /> up above, don’t share any sort of direct relationship, even though they might be right next to each other. They only “care” about parent <Parent /> and their own nested children.

Here's how uni-directional data-flow is established:

  • Props (downward movement) Simplest form of passing data into children is via props
render() {
...
  return <Link to={'https://github.com/fosteman/'}>MyGitHub</Link>;
}
Enter fullscreen mode Exit fullscreen mode

<Link> gets his location descriptor (url) via property to

  • Handlers (upward movement) Function objects can be passed as arguments to other functions, grace to > everything in JS is an object.
const IncrementField = (props) => (
  <div>
    {props.currentCount}
    <input onChange={props.onChange} />
  </div>
);

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = { counter: 0 };
    // because components created with classes don’t auto bind component methods, you need to bind them to `this` in the constructor.
    this.handleIncrement = this.handleIncrement.bind(this)
  }
  handleIncrement(amount = 1) {
    // note that immutable state isn't directly modified, instead .setState is used
    this.setState({ counter: this.state.counter + amount });
  }
  render() {
    return <IncrementField currentCount={this.state.counter} onChange={this.handleIncrement} />
  }
}
Enter fullscreen mode Exit fullscreen mode

Method handleIncrement defined on Parent component is handed onClick={this.handleIncrement} via properties to the child component <IncrementField />

This way the child component can push data up without having a least idea of how parent will handle it.

Redux

It is a logical continuation of React state. Should one require to centralize his data in the application, Flux comes in handy.

It is a pattern for managing data flow in your application. The most important concept is that data flows in one direction.

Read my article about Redux!

Top comments (1)

Collapse
 
ericsonwillians profile image
Ericson Willians (R.D.)

I find it impossible to work on a complex application without Redux. Working with just props and handlers sounds unrealistic considering a real-world web application.