Understanding Data Flow in React.js

Yashaswi SahuYashaswi Sahu
2 min read

Sending Data from Child to Parent

A child component can send data to a parent component by using a function passed down as a prop from the parent.

// ParentComponent.jsx
const [childData, setChildData] = useState("");

const handleData = (data) => {
  setChildData(data);
};

<ChildComponent sendData={handleData} />

// ChildComponent.jsx
props.sendData("Data from Child");

Sending Data from Child to Child

For one child component to send data to another child component, the data needs to go through their common parent. The parent can then pass the data to the other child.

// ParentComponent.jsx
const [data, setData] = useState("");

<ChildComponent setData={setData} />
<AnotherChildComponent data={data} />

Sending Data from Parent to Child

In React, a parent component can send data to a child component using props. This allows the parent to control and pass data down to the child.

// ParentComponent.jsx
const ParentComponent = () => {
  const data = "Hello from Parent!";
  return <ChildComponent message={data} />;
};

// ChildComponent.jsx
const ChildComponent = ({ message }) => {
  return <div>{message}</div>;
};

Sending Data through API

You can send data to an API from a React component using fetch or axios. This allows you to interact with a backend server.

// ExampleComponent.jsx
import axios from 'axios';

const sendDataToAPI = (data) => {
  axios.post('https://api.example.com/data', { data })
    .then(response => {
      console.log('Data sent:', response);
    })
    .catch(error => {
      console.error('Error sending data:', error);
    });
};

sendDataToAPI("Data to send");
0
Subscribe to my newsletter

Read articles from Yashaswi Sahu directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Yashaswi Sahu
Yashaswi Sahu