React 16
React Context API

What's the problem before React 16?

What's the problem before React 16?

  • Old version React context API Problem

Old version problem in

React context

class Green extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    <div>{this.context.number}</div>
  }
)

Green.contextTypes = {
  number: React.PropTypes.string
};

const Blue = (props) => (
  <div>
    <Green />
  </div>
)
 
class Red extends Component {
  state = {
    number : 10
  }

  getChildContext() {
    return {color: "purple"};
  }

  render() {
    return  (
      <div>
        {this.state.number}
        <Blue number={this.state.number} />
      </div>
    )
  }
}

Red.childContextTypes = {
  number: PropTypes.string
};

shouldComponentUpdate

See the Example

const Green = (props) => (
  <div>{props.number}</div>
)

const Blue = (props) => (
  <div>
    <Green number={props.number} />
  </div>
)
 
class Red extends Component {
  state = {
    number : 10
  }

  render() {
    return  (
      <div>
        {this.state.number}
        <Blue number={this.state.number} />
      </div>
    )
  }
}

What's React Context?

  • application global state

  • state management

By using React Context

const AppContext = React.createContext();

class AppProvider extends Component {
  state = {
    number: 10
  }

  render() {
    return (
      <AppContext.Provider value={this.state}>
        {this.props.children}
      </AppContext.Provider>
    );
  }
}

const Green = () => (
  <div>
    <AppContext.Consumer>
      {(context) => context.number}
    </AppContext.Consumer>
  </div>
)

const Blue = () => (
  <div>
    <Green />
  </div>
)
 
class Red extends Component {
  render() {
    return  (
      <AppProvider> 
        <div>
          <AppContext.Consumer>
            {(context) => context.number}
          </AppContext.Consumer>
          <Blue />
        </div>
      </AppProvider>
    )
  }
}

各取所需的概念XD

More Useful Example

  • 多國語言: https://codesandbox.io/s/741002jpxx

  • Modal: https://codesandbox.io/s/k0x8n7v1vo

  • Theme change:
    https://codesandbox.io/s/jn9l4689ky

React

By Stanney Yen

React

  • 297