Passing Data between Components

Learn via video courses
Topics Covered

Overview

In a react app, we generally create several components which interact with each other for implementing some feature in our react app. To do so, components pass data between each other i.e from parent to child, from child to parent, and also among siblings. Thus, passing data between components is an important aspect of react app.

Creating a React Project

For a better understanding of passing data between components, let's create a small classroom project, which consists of a teacher and three students. Each of them has a board with them on which they will write. We will get a better understanding of functionality as we proceed with the project.

How to Create React App?

To create react app, go to the console and type this command:

Declaring the Project Structure

We have created a react project for the classroom as discussed above:

App Component

[App.js]

Parent Component

[TeacherBoard]

Child Component

[StudentBoard]

[Topic Component]

This is the code to create our classroom project, with a little css the project will look somewhat like this:

classroom-project

Passing Data from Parent to Child

Passing data from parent to child is most used in generally react apps. Generally, we use react props to pass data from parent to child.

Props Declaration

Props are arguments passed into React components. Props are passed to components via HTML attributes.

Let's declare a prop name homework which has value as the text written on the board by the teacher.

Code Implementation

We will use react useState hook in the App component to keep a state of homework.

We have to create a function in the Parent component which will change the homework according to any update in the teachers' board.

Now let's say we have updated the state of homework and it has value as text return on the teacher's board currently. Now we have to pass the homework to Child components to update their boards.

so, After updating all the above-discussed code, our project code will look like this:

[App.js]

[TeacherBoard]

[StudentBoard]

Output:

Now let's say, the teacher writes Holiday Homework on the board, then the children's components i.e student board also have the same text on their boards. As we passed data from Parent {Teachers} to child components {Students}, the output will look like this:

passing-of-prop-from-parent-to-child

As we change the text on teacher boards student boards are also changing their text. So we have just seen the passing of data from parent to child component.

Passing Data from Child to Parent

In the above example, the student board is change its text according to its parent i.e teacher's board text. Now to understand the concept of passing data from child to parent, let's create a new functionality.

Let us create a doubt board which will be the child of the teacher board component, whenever a student writes on this board the doubt will be displayed under the current doubt section which will be in the teacher board component.

Callback Declaration

A callback is a function passed as an argument to another function. we will pass a callback function name updateDoubt from parent teacherBoard to child doubtboard

Code Implementation

we have to create a state for doubt using the useState hook.

Along with it, we must have a function that will update the doubt state using setDoubt.

We have to create a new component, let's name it DoubtBoard and an h3 under which we display currentDoubt.

[DoubtBoard component]

And in last we have to include it in our TeacherBoard component.

so after all these changes teacherBoard component will look like this:

Now let's understand the flow of code, As we have to update the value of Current Doubt according to a child component DoubtBoard. So we have to pass data from the child component to the parent component. It seems to be a challenging thing when you first see it, but we have one way to do so i.e by using callback functions.

We have created a doubt state and also have a function updateDoubt which should update doubt when the text on doubtBoard changes. so we will pass the updateDoubt function as a callback function. we can see the DoubtBoard component updating doubt using the updateDoubt function when the text on doubtBoard is changing.

Output:

Let's test what we have done so far, let's suppose a student asks a doubt using doubtBoard : "How we can pass data between components?", in this case, the Current Doubt section will display the same doubt under it.

passing-data-from-child-to-parent

Passing Data among Siblings

So far we have learned, about passing data from parent to child and passing data from child to parent.

Now many times we need to pass between siblings. To understand this let's define an Exam Hall project. There will be three StudentBoards and students will pass answers between each other if the text on any board changes then this will result in the same change in all the boards.

[App component]

[studentBoard component]

Now we have three ways to pass data between siblings. Let's explore them one by one.

Callbacks and Props

Back to callbacks and props, this is the easiest way to transfer data among siblings. In this method, we will create one state for the answer.

We will also create a function that has the functionality to change the state of the answer using setAnswer and then we will pass this function and answer state as a prop to all the siblings.

After all the changes discussed our components will be:

[App component]

[studentBoard component]

Hence, this will successfully pass data between siblings, and if a student writes "Passing data between siblings using props and callbacks" on the board and all of the boards have the same text on them.

passing-of-data-between-siblings-using-props-and-callbacks

Using Redux

In the above-discussed methods, we have passed data from either parent to child or child to parent. But in the actual application, we may be needed to pass data to a component that is not a direct child or parent. In that case, it will be tough, lengthy, and confusing to pass props and callbacks again and again. So we will use something called redux. Redux help us to create a store for different states and use them in our project freely.

usefullness-of-redux

So let's start with the basic Exam Hall project but this time we will add a new sibling component to make the example more interesting. We will have a topperBoard component. As the topper's board text changes our student board text also changes.

[TopperBoard Component]

[App Component]

[studentBoard component]

So the project will look like this:

exam-hall-project

Setup Redux

we will use redux and redux-toolkit here, to install these dependencies we have to use:

Now, let's start with the implementation part, in redux, we will have some of these components:

  1. Store:
    It is an object that has the application's state. This object is accessible with help of the provider in the files of the project. Sending an action to it is the only way to change the state inside it.

  2. Reducers:
    The pure functions known as reducers hold the calculation and logic that have to be done on the state. These functions accept the action type and the initial state of the state being used. It responds with the new state after updating the state.

    To create a store we will use configureStore and to update and use any state we will use useDispatch and useSelector respectively.

    we will use slices to store and change states. To create slices we have to use createSlice.

    After implementing all the points discussed above our studentBoard and topperBoard component will be :

[studentBoard Component]

[topperBoard Component]

Along with this our main component will also change which will be implementing store and provider for the whole project and in addition to this, we will have a reducer for the answer.

[main component]

[answer reducer]

This will be sufficient to do our task, we can create multiple reducers in our project for different tasks.

Hence, when the topper writes "Passing data between siblings using Redux" on board. Then studentBoards will look like this:

passing-data-between-siblings-using-redux

ContextAPI

The React Context API is a way for React apps to effectively create passable global variables. This is an alternative way of "prop drilling" or moving props from grandparents to children, parents, etc. Contexts are also acknowledged as a simpler, more lightweight approach to state management using Redux.

How ContextAPI Works?

The primary concept is passing the parameters to the following function as you move on. React contextApi has two main things:

  1. Provider:
    A Provider, as its name suggests, is a component that provides state to its children. It will hold the "store" and be the parent of all the components that might need that store.
  2. Consumer:
    A consumer is a component that consumes and uses state.

Let's start with the basic Exam Hall project, which will have one topperBoard and three studentBoard.

Now to use contextApi we will create a context AnswerContext and then will we wrap all the components to whom we have to pass data under it.

[App component]

[TopperBoard component]

[studentBoard Component]

Now let's suppose the topper writes "Passing data between using ContextAPI" on board. Then studentboards will look like this:

passing-of-data-using-contextapi

Conclusion

In this article, we have learned about:

  • Different ways to pass data between components.
  • We can pass data from parent to child using props.
  • To pass data from child to parent, we can use callback functions.
  • Passing data between siblings is much more complex than the other two cases, we can use props along with callbacks for the same.
  • Redux provides a very useful way to pass data between any components by creating a store.
  • React also provides us with contextAPI, through which we can create context, then provide and consume data through it.
  • we learned about how to use context API for passing data between components.