This article describes how to use the React Context API. Before using the Context API, we need to know why we are using it. ❓

Why are we using the Context API

Considering that components can be layered, if a large number of… Props or propName={this.props. PropValue} causes code to be ugly 🤢 :

Layer by layer, it goes like this:

<App>
    <Switcher toggleState={this.state.toggle}>
        <Pannel toggleState={props.toggleState}>
            <div onClick={handleClick}>{props.toggleState ? '✔' : '❌'}
Copy the code

So by introducing the Context API, we can get data directly from the Context across the hierarchy:

How to use

  • Then create the provider 👇
  • The first step is to introduce the built-in React Context API 📦
  • Finally, create consumer 👆

Create the Provider

Add a file called togglecontext.js as a context 📜 that defines a set of states and functions to be used across the hierarchy

import React, { createContext } from 'react'

// 1. Create the context using createContext
const ToggleContext = createContext({
    toggle: true.handleToggle: (a)= >{}})// 2. Create Provider
export class ToggleProvider extends React.Component {

    // Pay attention to the order of writing; HandleToggle as an arrow function can't bind so you need to put it on top; If you don't like the order you can write the normal function down here but remember bind
    handleToggle = (a)= > {
        this.setState({ toggle:!this.state.toggle })
    }

    // 2-1
    state = {
        toggle: true.handleToggle: this.handleToggle
    }

    render() {
        // 2-2. Use the value of the Provider component to provide state
        return (
            <ToggleContext.Provider value={this.state}>
                {this.props.children}
            </ToggleContext.Provider>Create Consumer export const ToggleConsumer = ToggleContext.ConsumerCopy the code

The above code is divided into three main parts:

/ / create the Context
const ToggleContext = createContext()

/ / create the Provider
export class ToggleProvider extends React.Component {}

/ / to create a Consumer
export cnost ToggleConsumer = ToggleContext.Consumer
Copy the code

Let’s go through the steps 🏃

  • First, we need to introducecreateContextContext and call, passing in what we want to use in other tiers of componentsstateAnd changestateStudent: Notice the method herestateAnd the method is just a “skeleton” behind itProvideroverwrite
  • So let’s createProviderHere the head maintains the realstate, and through therenderInside the functionContext.ProviderThe component’svalueProperty provides these methods
  • Then create aConsumer, directly exportContext.ConsumerFor external use

The use of the Provider

The ToggleProvider component wraps a set of shared states, which we add directly to the App component to use:

import React from 'react';
import { ToggleProvider } from './ToggleContext' // 1. Obtain Provider

function App() {
  // 2-1. Use ToggleProvider
  // 2-2. If there are other components can share state
  return (
    <ToggleProvider>
      <Switcher></Switcher>{/* Other components can still access the shared state */}</ToggleProvider>
  );
}

// ...
export default App;
Copy the code

It is easier to use a Provider and wrap it in the upper layer as a parent component. If there are multiple other components inside the component, they can all share the state provided by the Provider

The use of Consumer

  • Render in the Render function using the state property passed by the props directly from the Consumer
  • If a method needs to be called, the function passed by props can be called
import React from 'react';
import { ToggleProvider, ToggleConsumer } from './ToggleContext' Obtain Provider and Consumer

function App() {
  return (
    <ToggleProvider>
      <Switcher></Switcher>
    </ToggleProvider>
  );
}

const Switcher = (a)= > {
  return <Pannel />} const Pannel = () => {// Const Pannel = () => {// const Pannel = () => {<ToggleConsumer>
      {({ toggle, handleToggle }) => <div onClick={()= > handleToggle()}>{ toggle ? '✔' : '❌'}</div>}
    </ToggleConsumer>
  )
}

export default App;
Copy the code

Call props directly from within the child component

summary

Here’s a quick version of Context:

  • Create a context named color using createContext
  • The value property of the Provider is used to transfer values
  • The values are received through the Consumer’s props
import React, { createContext } from "react"; const { Provider, Consumer } = createContext("color"); // Create a Context reference Provider and Consumer Class DeliverComponent extends React.Component {// Maintain a state state = {color: 'orange', handleClick: () => { this.setState({ color: 'red' }) } } render() { return ( <Provider value={this.state}> <MidComponent /> </Provider> ) } } const MidComponent = () => <Receiver />; Const Receiver = () => (Consumer <Consumer> {({color, handleClick }) => <div style={{ color }} onClick={() => { handleClick() }}> Hello, this is receiver.</div>} </Consumer> ); const App = () => <DeliverComponent />; export default App;Copy the code

Reference:

  • https://blog.usejournal.com/sharing-state-using-reacts-context-api-bc2db94da46d