How to pass data to a child component using React Context API?

React Context API is an elegant way of passing data to child components. Context API is a good replacement of Redux for small applications. In this article, we will look into the steps of passing data to a child component.

As the context API works like a tree structure, the data binding is one way. From the parent, we can pass the data and the child component will consume that data. But we can not set data to the context from a child component that a parent will use.

The following are the code base for Context API one-way data-binding:

Declare the context in a separate file

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

const AppContext = React.createContext();

export default AppContext;

Now from the parent component, we need to provide the data like below:

// Home.js
import React, {Component, Fragment} from 'react';

import AppContext from "../AppContext";
import Company from "./Company";


class Home extends Component {

    render() {

        return (
            <Fragment>
                 <AppContext.Provider value={{data: {id: 35355, name: "Google Inc"}}}>
                     <Company/>
                 </AppContext.Provider>
            </Fragment>
        );
    }
}
export default Home;

Finally from the child component, we need to consume data like below:

import React, {Fragment, useContext} from 'react';
import AppContext from "../AppContext";

const Company = () =>{
    const context = useContext(AppContext);
    return(
        <Fragment>
            <h1>{context.data.name}</h1>
        </Fragment>
    )
};
export default Company;