React Context API


Tue Jun 29 2021 10:17:43 GMT+0000 (Coordinated Universal Time)

Saved by @hisam #react.js #javascript #react

//Provider Component
import React, { Component } from 'react';

// Create new context
const MyContext = React.createContext();

// Create the Provider that will pass down state and methods to the rest of the application.
class MyProvider extends Component {
  state = {
    name: 'Dominic',
    age: 28,
  render() {
    return (
      <MyContext.Provider value={{
        state: this.state,
        addYear: () => this.setState({
          age: this.state.age + 1

// Create the consumer that will consume the data provided by the Provider.
class Company extends Component {
  render() {
      <div className="company">
          {(context) => (
            //Fragment added here since you can only return one child
              <p>Welcome to {}</p>
              <p>We are {context.state.age} years old!</p>
              <button onClick={context.addYear}>Add Year</button>

// We'll nest our Consumer inside another component just to show that we don't need to pass props to each component.
const Companies = () => (
    <Company />

class App extends Component {
  render() {
    return (
      // Ensure the provider wraps all the components you want to share data between.
        <div className="App">
          <Companies />

export default App;

The React Context API aims to solves the prop drilling issue by way of a fairly straight forward Provider to Consumer relationship. This makes passing data between components that are not necessarily direct descendants of each other much easier.