Pass data between React Components using Hooks and Context
Often you would have faced trouble in passing data between various components in React. In this tutorial, I’d demonstrate the most simple approaches to pass data from Parent to Child, Child to Parent and Child to Child. We’ll make use of functional components, React Hooks and React Context API to achieve this.
So let’s set-up our environment and dive straight into the tutorial.
We will use create-react-app to create a new boilerplate react application.
If you don’t have create-react-app installed then you may run the command given below in the terminal to set it up.
npm install -g create-react-app
Next, set up the React boilerplate application in your desired directory by using the command given below in terminal
create-react-app context
We’ll move into the folder in which our app has been set up and then start the development server.
//Change directory
cd context//Start VSCode
code . //Start the Development Server
yarn start
P.S-If you’re stuck at any point you can refer this Github Repository.
Pass Data from Parent to Child
We’ll create two files Parent.js and Child.js in the src folder and the text input given by the user in the Parent Component should appear in the Child component.
The output of this example is as shown below:
After taking an input it will appear as:
The code for this example has been shown below.
Pass Data from Child to Parent
For this, we’ll use a global storehouse to store the data and that data will be fetched by the Parent. So we’ll make use of React Context API for this.
The text input given by the user in the Child Component should appear in the Parent component.
The output of this example is as shown below:
After taking an input it will appear as:
createContext
creates a Context object. When React renders a component that subscribes to this Context object it will read the current context value from the closest matching Provider
above it in the tree.
AppContext.Provider
component accepts a value
prop to be passed to consuming components that are descendants of this Provider. One Provider can be connected to many consumers. Providers can be nested to override values deeper within the tree.
A reducer
is a function that determines changes to an application’s state. It uses the action it receives to determine this change.
The code for this example has been shown below.
Pass Data Between Siblings
To pass data from Child1 to Child2, we’ll combine the above methods.
The text input given by the user in the Child1 Component should appear in the Child2 component.
The output of this example is as shown below:
After taking an input it will appear as:
The code for this example has been shown below.
Congratulations, you just learnt state management using React Context API!