kurosame’s diary

フロントエンド中心です

React の Context API について

ContextAPI

  • v16.3 から追加された機能
  • React のみでいい感じの State 管理ができる
  • Redux とは別の選択肢ができただけと思って良い認識

従来の State 受け渡し

class Parent extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      count: 1
    }
  }

  render() {
    return (
      <div>
        親:
        {this.state.count}
        <Child count={this.state.count} />
      </div>
    )
  }
}

const Child = props => (
  <div>
    子:
    {props.count}
    <Grandchild count={props.count} />
  </div>
)

const Grandchild = props => (
  <div>
    孫:
    {props.count}
  </div>
)

ReactDOM.render(<Parent />, document.querySelector('#app'))

結果

f:id:kurosame-th:20181105172314p:plain

ContextAPI を使った State 受け渡し

const { Provider, Consumer } = React.createContext()

class Parent extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      count: 2
    }
  }

  render() {
    return (
      <Provider value={{ state: this.state }}>
        <div>
          親:
          {this.state.count}
          <Child />
        </div>
      </Provider>
    )
  }
}

const Child = () => (
  <div>
    <Grandchild />
  </div>
)

const Grandchild = () => (
  <Consumer>
    {({ state }) => (
      <div>
        孫:
        {state.count}
      </div>
    )}
  </Consumer>
)

ReactDOM.render(<Parent />, document.querySelector('#app'))

結果

f:id:kurosame-th:20181105173941p:plain

今回は State のみだったが、Action も同じように渡せる

考察

  • Redux でやってたことは普通に実現できそう
  • よく言われているが、小規模であれば Context API はありだが、大規模であれば Redux 等を使った方が良さそう
    • Provider が肥大化すると、メンテナンス性が低そう。ネストもするので、可読性も悪い