Interview question - React (9): React's Context: Implementing non-parent-child component communication

In React, communication between components is one of the key issues in building complex applications. Although React's data flow is usually top-down, that is, passed from parent component to child component, sometimes we need to implement communication between non-parent and child components. To solve this problem, React introduces Context, a mechanism that can pass data across levels.

1. Overview of React’s Context

Context is a global state management solution that allows us to share data across the component tree without passing it through props. Context is usually used to share common data between components, such as themes, user login status, etc.

2. Use Context to implement non-parent-child component communication

Through Context, we can implement communication between non-parent and child components. The following are the implementation steps:

1. Create Context:

First, we need to create a Context. This can be done anywhere, but usually we will define the Context in a separate file.

// DataContext.js
import React from 'react';

const DataContext = React.createContext();

export default DataContext;
2. Provide data:

In the parent component that needs to share data, we use <DataContext.Provider>to provide the data. This Provider will wrap the child components so that these child components can access the provided data.

// ParentComponent.js
import React from 'react';
import DataContext from './DataContext';

class ParentComponent extends React.Component {
  state = { data: 'Hello from parent!' };

  render() {
    return (
      <DataContext.Provider value={this.state.data}>
        {this.props.children}
      </DataContext.Provider>
    );
  }
}
3. Usage data:

In child components, we can get the provided data through useContexthooks or .Context.Consumer

// ChildComponent.js
import React, { useContext } from 'react';
import DataContext from './DataContext';

function ChildComponent() {
  const data = useContext(DataContext);

  return <p>Data from parent: {data}</p>;
}

Guess you like

Origin blog.csdn.net/weixin_42560424/article/details/132696083