1. Context

Context is mainly used to solve the problem of data transfer when multi-tier components are nested.

Context is designed to share data that is “global” to a component tree.

The problem with using Context is that it makes components less reusable.

1.1 Usage Example

The demo ├ ─ ─ myContext. Js# the context object├ ─ ─ myComponent. Js# child components└ ─ ─ app. Js# the root component
Copy the code

myContext.js

export const langList = {
  en: { text: 'BUTTON' },
  zh: { text: 'button'}};export const MyContext = React.createContext({
  lang: langList.en, / / the default value
  onChange: () = > {}, // Modify the context default function
});
Copy the code

myComponent.js

import { MyContext, langList } from './myContext';

class MyComponent extends React.Component {
  render() {
    let props = this.props;
    let data = this.context;
    return (
      <button
        {. props} // You can call the incomingonChangeMethods to modifycontext
        onClick={()= > data.onChange(langList.en)}>
        {data.lang.text}
      </button>); }}// Ensure that the default values can be rendered
// Default values will be rendered when no Provider value is provided
MyComponent.contextType = MyContext;

export default MyComponent;
Copy the code

Functional components can use context.consumerAPI: myComponent.js

import { MyContext, langList } from './myContext';

function MyComponent(props) {
  return (
    <MyContext.Consumer>
      {
        data => (
          <button
            {. props}
            onClick={()= > data.onChange(langList.en)}>
            {data.lang.text}
          </button>)}</MyContext.Consumer>
  );
}
Copy the code

app.js

import { MyContext, langList } from './myContext';
import MyComponent from './myComponent';

class App extends React.Component {
  // Context modification method for the root component
  this.onChange = (lang) = > {
    this.setState({ lang });
  };

  state = {
    value: {
      lang: langList.zh,
      onChange: this.onChange,
    }
  };
  
  render() {
    return (
      // Be careful not to assign objects directly here
      // Since each render is a new object, the consumer will accidentally render
      // <MyContext.Provider value={{ lang: this.state.lang, onChange: this.onChange }}>
      // Should be placed in state
      <MyContext.Provider value={this.state.value}>// For the sake of simplicity, intermediate components are not nested here<MyComponent />
      </MyContext.Provider>
    );
  }
}

ReactDOM.render(<App />.document.root);
Copy the code

1.2 Using multiple Contexts

The root component nested context. Provider, and the child component nested context. Provider.

2. useContext

Solve the problem of using Context conveniently in functional components instead of context.consumerAPI. Receives a context object (the return value of React. CreateContext) and returns the current value of the context.

const value = useContext(MyContext);
Copy the code

Components that call useContext are always rerendered when the context value changes.

import { MyContext } from './myContext';

function MyComponent(props) {
  const data = useContext(MyContext);

  return (
    <button
      {. props} >
      {data.lang.text}
    </button>
  );
}
Copy the code

The End. Reference Zh-hans.reactjs.org/docs/contex….