# One Way Data Flow

One-way direction data flow eliminates multiple states and deals with only one which is usually inside the store. To achieve that our Store object needs logic that allows us to subscribe for changes:

```javascript
var Store = {
  _handlers: [],
  _flag: '',
  onChange: function (handler) {
    this._handlers.push(handler);
  },
  set: function (value) {
    this._flag = value;
    this._handlers.forEach(handler => handler())
  },
  get: function () {
    return this._flag;
  }
};
```

Then we will hook our main App component and we'll re-render it every time when the Store changes its value:

```javascript
class App extends React.Component {
  constructor(props) {
    super(props);
    Store.onChange(this.forceUpdate.bind(this));
  }

  render() {
    return (
      <div>
        <Switcher
          value={ Store.get() }
          onChange={ Store.set.bind(Store) }/>
      </div>
    );
  }
}
```

Notice that we are using forceUpdate which is not really recommended.

Normally a high-order component is used to enable the re-rendering. We used forceUpdate just to keep the example simple.

Because of this change the Switcher becomes really simple. We don't need the internal state:

```javascript
class Switcher extends React.Component {
  constructor(props) {
    super(props);
    this._onButtonClick = e => {
      this.props.onChange(!this.props.value);
    }
  }

  render() {
    return (
      <button onClick={ this._onButtonClick }>
        { this.props.value ? 'lights on' : 'lights off' }
      </button>
    );
  }
}
```

The benefit that comes with this pattern is that our components become dummy representation of the Store's data. It's really easy to think about the React components as views (renderers). We write our application in a declarative way and deal with the complexity in only one place.

## Related links:

* <https://www.startuprocket.com/articles/evolution-toward-one-way-data-flow-a-quick-introduction-to-redux>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://christer-johansson.gitbook.io/learn-react-now/design-patterns-and-techniques/24.one-way-data-flow.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
