SoFunction
Updated on 2025-04-06

Several common methods for React to implement communication between components

How to implement communication between components in React?

1. Props delivery

The most direct way of communication is to pass data from the parent component to the child component through props. The parent component passes data to the child component through attributes, and the child component can passAccess these data.

Sample code:

import React from 'react';

class ParentComponent extends  {
  render() {
    const message = "Hello from Parent!";
    return (
      <div>
        <h1>Parent Component</h1>
        <ChildComponent message={message} />
      </div>
    );
  }
}

class ChildComponent extends  {
  render() {
    return (
      <div>
        <h2>Child Component</h2>
        <p>{}</p>
      </div>
    );
  }
}

export default ParentComponent;

In this example, ParentComponent passes data to ChildComponent through the message property, which accesses and displays the message.

2. Callback function

In addition to passing data through props, the parent component can also communicate with the child component through callback functions. A child component can call functions from the parent component, update states with the parent component or pass data.

Sample code:

import React from 'react';

class ParentComponent extends  {
  handleChildMessage = (msg) => {
    alert("Message from Child: " + msg);
  }

  render() {
    return (
      <div>
        <h1>Parent Component</h1>
        <ChildComponent onSendMessage={} />
      </div>
    );
  }
}

class ChildComponent extends  {
  sendMessage = () => {
    ("Hello from Child!");
  }

  render() {
    return (
      <div>
        <h2>Child Component</h2>
        <button onClick={}>Send Message</button>
      </div>
    );
  }
}

export default ParentComponent;

In this example, there is a button in the child component. After clicking, the sendMessage method will be triggered. By calling the method in the parent component, the message sent by the child component pops up in the parent component.

3. Context API

For deeper component nesting, passing directly through props can lead to props drilling (i.e., passing props from multiple layers), in which case, using React's Context API allows you to share data between multiple components without having to pass through each layer.

Sample code:

import React from 'react';

// Create Contextconst MessageContext = ();

class ParentComponent extends  {
  state = {
    message: "Hello from Parent via Context!",
  };

  render() {
    return (
      &lt; value={}&gt;
        &lt;NestedComponent /&gt;
      &lt;/&gt;
    );
  }
}

class NestedComponent extends  {
  render() {
    return (
      &lt;div&gt;
        &lt;h1&gt;Nested Component&lt;/h1&gt;
        &lt;ChildComponent /&gt;
      &lt;/div&gt;
    );
  }
}

class ChildComponent extends  {
  static contextType = MessageContext;

  render() {
    return (
      &lt;div&gt;
        &lt;h2&gt;Child Component&lt;/h2&gt;
        &lt;p&gt;{}&lt;/p&gt;
      &lt;/div&gt;
    );
  }
}

export default ParentComponent;

In this example, a Context is created in ParentComponent and the value is provided using Provider. ChildComponent directly accesses the value in context through static contextType = MessageContext.

4. Redux

When applications become complex, using Redux for state management can help us centrally manage the state of the application and enable communication between components. Redux saves all states of the application in a store and manages state changes through actions and reducers.

Sample code:

import React from 'react';
import { createStore } from 'redux';
import { Provider, connect } from 'react-redux';

// Redux reducer
const initialState = { message: "Initial Message" };
const messageReducer = (state = initialState, action) => {
  switch () {
    case 'UPDATE_MESSAGE':
      return { ...state, message:  };
    default:
      return state;
  }
};

// Create Redux store
const store = createStore(messageReducer);

// Parent Component
class ParentComponent extends  {
  updateMessage = () => {
    ("New Message from Parent!");
  }

  render() {
    return (
      <div>
        <h1>Parent Component</h1>
        <button onClick={}>Update Message</button>
        <ChildComponent />
      </div>
    );
  }
}

// Child Component
const ChildComponent = ({ message }) => {
  return (
    <div>
      <h2>Child Component</h2>
      <p>{message}</p>
    </div>
  );
};

// Connect components to Redux store
const mapStateToProps = state => ({
  message: ,
});

const mapDispatchToProps = dispatch => ({
  updateMessage: (msg) => dispatch({ type: 'UPDATE_MESSAGE', payload: msg }),
});

const ConnectedParentComponent = connect(null, mapDispatchToProps)(ParentComponent);
const ConnectedChildComponent = connect(mapStateToProps)(ChildComponent);

// App Component
const App = () => (
  <Provider store={store}>
    <ConnectedParentComponent />
  </Provider>
);

export default App;

In this example, we manage the status through Redux,ParentComponentCan be passeddispatchUpdate the message, andChildComponentThe current message is directly obtained from the Redux store.

Summarize

In React, there are several ways to communicate between components, including props delivery, callback functions, Context API, and state management tools such as Redux. Which method to choose depends on the complexity and requirements of the application. Simple applications can use props and callback functions directly, while complex applications may require the Context API or Redux to handle state. By understanding and mastering these communication methods, you will be able to build more efficient and maintainable React applications.

The above is the detailed content of the example code for React to implement communication between components. For more information about communication between React components, please pay attention to my other related articles!