React: Context

by Troy Rhinehart

What
Why
HOw

What
Why
HOw

https://medium.com/@mweststrate/how-to-safely-use-react-context-b7e343eff076#.t01z8haut

 

Context is a very powerful feature in React, with lots of disclaimers around it. A bit like the forbidden fruit in paradise.

 

What
Why
HOw

https://facebook.github.io/react/docs/context.html

 

IN SOME CASES, YOU WANT TO PASS DATA THROUGH THE COMPONENT TREE WITHOUT HAVING TO PASS THE PROPS DOWN MANUALLY AT EVERY LEVEL. YOU CAN DO THIS DIRECTLY IN REACT WITH THE POWERFUL "CONTEXT" API.

 

Context can also let you build an API where parents and children communicate.

 

What
Why NOT?
HOw

https://facebook.github.io/react/docs/context.html

 

If you want your application to be stable, don't use context. It is an experimental API and it is likely to break in future releases of React.

 

If you aren't an experienced React developer, don't use context.

 

React has an API to update context, but it is fundamentally broken and you should not use it.

 

The problem is, if a context value provided by component changes, descendants that use that value won't update if an intermediate parent returns false from shouldComponentUpdate.

What
Why
HOw

Component.contextTypes = {
  example: React.PropTypes.string
};

If contextTypes is defined within a component, the following lifecycle methods will receive an additional parameter, the context object

  • constructor(props, context)

  • componentWillReceiveProps(nextProps, nextContext)

  • shouldComponentUpdate(nextProps, nextState, nextContext)

  • componentWillUpdate(nextProps, nextState, nextContext)

  • componentDidUpdate(prevProps, prevState, prevContext)

What
Why
HOW to set

class SetContextComponent extends React.Component {

  static childContextTypes = {
    example: React.PropTypes.string
  };

  getChildContext(){
    return {
      example: "Hello World"
    };
  }

  render(){
    return (
      <div>
        <Some>
          <Thing>
            <Deep>
              <GetContextComponent/>
            </Deep>
          </Thing>
        </Some>
      </div>
    );
  }

}

Class Component

What
Why
HOW to get

class GetContextComponent extends React.Component {

  static contextTypes = {
    example: React.PropTypes.string
  };

  render(){
    const { example } = this.context;
    return <h1>{ example }</h1>
  }

}
function GetContextComponent(props, context) {
  const { example } = context;
  return <h1>{ example }</h1>
}

GetContextComponent.contextTypes = {
  example: React.PropTypes.string
};

Class Component

Stateless Functional Component

DEMOS!

Demo 1 - Basic Example

Demo 2 - State Example

Demo 3 - Nested Example

 

where

103 places in our private github

 

guac-widget-core

src/UX/Base/index.js

src/UX2/Base/Base.js

 

Thank you!

questions?

React: Context

By gingur

React: Context

The WHAT, WHY, HOW of React Context

  • 191