Get rich quick with…

React Context – New! 16.3
Patrick Hund | frontend developer at eBay Tech Berlin | @wiekatz

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

Tin Can Telephone

AdvertisingContext.js


import { createContext } from 'react';

export default createContext(() => {});
            

AdvertisingProvider.js


import React, { Component } from 'react';
import AdvertisingContext from './AdvertisingContext';
import Advertising from './Advertising';

export default class extends Component {
  constructor(props) {
    super(props);
    this.advertising = new Advertising(props.config);
  }

  render() {
    return (
      <AdvertisingContext.Provider value={this.advertising.activate}>
        {this.props.children}
      </AdvertisingContext.Provider>
    );
  }
}
                    

AdvertisingSlot.js


import React, { Component } from 'react';
import AdvertisingContext from './AdvertisingContext';

class AdvertisingSlot extends Component {
  componentDidMount() {
    const { activate, id } = this.props;
    activate(id);
  }

  render() {
    return <div id={this.props.id} />
  }
}

export default props => (
  <AdvertisingContext.Consumer>
    {activate => <AdvertisingSlot {...props} activate={activate} />}
  </AdvertisingContext.Consumer>
);

                    

// Old context API
import React, { Component } from 'react';
import PropTypes from 'prop-types';

class MyProvider extends Component {
  getChildContext() {
    return { message: 'hello world' };
  }
  render() {
    return this.props.children;
  }
}

MyProvider.childContextTypes = {
  message: PropTypes.string
};

class MyConsumer extends Component {
  render() {
    return <h1>{this.context.message}</h1>
  }
}

MyConsumer.contextTypes = {
  message: PropTypes.string
};

export default () => (
  <MyProvider>
    <MyConsumer />
  </MyProvider>
);
                    

// New context API
import React, {
  Component,
  createContext
} from 'react';

const { Provider, Consumer } = createContext();


function MyProvider({ children }) {
  return (
    <Provider value="hello world">
      {children}
    </Provider>
  );
}


function MyConsumer(props) {
  return (
    <Consumer>
      {message => <h1>{message}</h1>}
    </Consumer>
  );
}


export default () => (
  <MyProvider>
    <MyConsumer />
  </MyProvider>
);


                    

Don't use it for everything!

Other usecase examples
besides getting rich quick:

  • Internationalization
  • Layout themes
  • Tracking
github.com/technology-ebay-de/react-prebid

Thank you!

Follow me on Twitter:
@wiekatz

Patrick Hund, frontend developer at eBay Tech Berlin

View the slides:
technology-ebay-de.github.io/get-rich-quick-with-react-context/

View the code examples:
codesandbox.io/s/488y5n5kw
codesandbox.io/s/3rz877y8jm