An overview of the

Provider component: A parent component that shares a value with the consuming component

Consumer component: Shares all child components that provide the value of the component

React. CreateContext create a Context object

When React renders a consumer component that subscribes to the Context object, the component reads the current Context value from the closest matching Provider in the component tree

const MyContext = React.createContext(defaultValue);
Copy the code

instructions

  1. When the component belongs to the component treeThere is no matchingtoProviderTo set the default initial valuedefaultValueBefore it goes into effect.
  2. If it is toundefinedPassed to theProvidervalueIs the default initial valuedefaultValueIt won’t go into effect.

Context.Provider [can be nested (internal overwrites external)]

Each Context object returns a Provider React component, which allows the consuming component to subscribe to changes to the Context

< myContext. Provider value={set the value of the context required by the public component}>// Place components that require a common value
</MyContext.Provider>
Copy the code

instructions

  1. valueProperty value: Data value that is shared with the consuming component
  2. ProvidervalueWhen the value changes, all the consuming components within it are rerendered
  3. ProviderAnd its internalconsumerComponents are not subject toshouldComponentUpdateDelta function, so whenconsumerA component can be updated if its ancestor component exits the update

When value is an object, when the provider parent rerenders [value is given a new object], it may cause the consumer child to render unnecessarily

[Solution: You can raise the value to state.]

Class. ContextType [subscription context]

// Method 1:
class MyClass extends React.Component {
  componentDidMount() {
    let value = this.context;
    /* After the component is mounted, use the value of the MyContext component to perform some side effects */
  }

  render() {
    let value = this.context;
    /* Render based on the value of the MyContext component */
  }
}

MyClass.contextType = MyContext;


// Method 2: public class fields
class MyClass extends React.Component {
  static contextType = MyContext;
 
  render() {
    let value = this.context;
    /* Render based on this value */}}Copy the code

instructions

  1. willReact.createContext()To create theContextObject assigned toclasscontextTypeProperty to subscribe tocontextcontent
  2. To subscribe tocontextCan be used in class componentsthis.contextIn order to getProviderComponent defined invalueValue to achieve some data sharing between components
  3. Can be accessed in any lifecycle of a class componentthis.context
  4. Subscribe to multiplecontextFor example, seeThe official documentation

Context.Consumer subscribes to changes to the Context and updates the value in the Context object.

Set the shared context as an object that can contain methods to modify the value of the corresponding context

import { MyContext } from './theme-context';

function ThemeTogglerButton() {
  The // Theme Toggler button not only gets the Theme value, it also gets a toggleTheme function from the context
  return (
    <MyContext.Consumer>
      {({theme, toggleTheme}) => (
        <button	onClick={toggleTheme}
          style={{backgroundColor: theme.background}}
        >
          Toggle Theme
        </button>
      )}
    </MyContext.Consumer>
  );
}

export default ThemeTogglerButton;
Copy the code

instructions

  1. contextFor the parent componentMyContext.ProviderThe component’svalueAttribute value [no need to re-subscribe]
  2. customerThe component accepts a function as its wrapper content with the corresponding function parametersproviderThe share set up in the componentvalueValue for the corresponding element to render

Context.displayname [define MyContext to display the name in devTool]

Change the name of the corresponding element shown in the development tool review element by assigning a value to the Context’s property displayName

const MyContext = React.createContext(defaultValue);
MyContext.displayName = 'MyDisplayName';

<MyContext.Provider> // DevTools displays as "myDisplayName.provider"
<MyContext.Consumer> // DevTools displays "myDisplayName.consumer"
Copy the code

The use of Context in a function component

Use useContext to get context content information

// context.ts
const MyContext = React.createContext(defaultValue);

export default MyContext;

// App.tsx
const [state, setState] = useState({});

<MyContext.Provider value={state}>
  <MyComponent />
</MyContext.Provider>

// MyComponent.tsx
import React, { useContext } from 'react';
import MyContext from './context';

const MyComponent = () = > {
  // Display values with state and change values with setState
  const { state, setState } = useContext(MyContext);

  return (
    /* Render work */)}export default MyComponent;
Copy the code

Used by the old Context API class component and function component

Outdated Context

// provider.tsx
class ContextProvider extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: {}}}// When the state or props changes, getChildContext is called
  getChildContext() {
    const { value } = this.state;
    return { value, changeValue };
  }

  // state value change function
  changeValue = (value) = > {
    this.setState({ value });
  }

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

ContextProvider.childContextTypes = {
  value: PropTypes.object
};

// App.tsx
<ContextProvider>
  <MyComponent />
</ContextProvider>

// Class child myComponent.tsx
class MyComponent extends React.Component {
  static contextTypes = {
    value: PropTypes.object
  };
  
  console.log(this.context); // { value: Object, changeValue: Function }
  
  render() {
    // Render}}// Function child myComponent.tsx
const MyComponent = (props, context) = > {

  console.log(this.context); // { value: Object, changeValue: Function }

  return (
    // Render
  )
}

MyComponent.contextTypes = {
  value: PropTypes.object
};
Copy the code