Context Concepts in React with Examples

In this blog, we will see “Context Concepts in React with Examples”. This blog will help you understand this important concept with ease.

Let’s get started. Shall we?

Context Concepts in React with Examples

React Context is a way of passing data through the component tree without having to pass props manually at every level. In this tutorial, we will cover the basics of React Context and how to use it in your React applications.

Creating a Context

To create a new context, we use the React.createContext() method. This method returns an object that contains a Provider and a Consumer component. The Provider component is used to provide the data to the tree, and the Consumer component is used to consume the data.

<code>import React from 'react';

const MyContext = React.createContext();
</code>

Providing data

To provide data to the context, we use the Provider component. We can wrap our component tree with the Provider component, and any component in the tree can consume the data.

<code>import React from 'react';

const MyContext = React.createContext();

function App() {
  const data = { name: 'John', age: 25 };
  return (
    <MyContext.Provider value={data}>
      <Child />
    </MyContext.Provider>
  );
}

function Child() {
  return (
    <MyContext.Consumer>
      {value => <p>{value.name} is {value.age} years old</p>}
    </MyContext.Consumer>
  );
}
</code>

In the example above, we have a data object that we want to provide to our component tree. We use the Provider component and pass the data object as the value prop. Then, in the Child component, we use the Consumer component to consume the data.

Consuming data

To consume data from the context, we use the Consumer component. The Consumer component receives a function as its child, and that function receives the current context value as its argument. We can then use that value to render our component.

<code>import React from 'react';

const MyContext = React.createContext();

function Child() {
  return (
    <MyContext.Consumer>
      {value => <p>{value.name} is {value.age} years old</p>}
    </MyContext.Consumer>
  );
}
</code>

In the example above, we have a Child component that consumes the data from the context using the Consumer component. We pass a function as the child of the Consumer component, and that function receives the value of the context as its argument. We can then use that value to render our component.

Setting default values

When we create a context, we can also provide a default value for the context. This default value is used when there is no Provider component above the Consumer component in the component tree.

<code>import React from 'react';

const MyContext = React.createContext({ name: 'Anonymous', age: 0 });
</code>

In the example above, we provide a default value for the context that will be used if no Provider component is above the Consumer component in the component tree.

Updating the context

To update the data in the context, we can use the setState method. We can define a state in the parent component, pass the state and a function to update the state as a value to the Provider component, and use this function to update the state in the Consumer component.

Let’s take a look at an example:

import React, { createContext, useState } from 'react';

export const MyContext = createContext();

const Parent = () => {
  const [data, setData] = useState('initial data');

  const updateData = (newData) => {
    setData(newData);
  };

  return (
    <MyContext.Provider value={{ data, updateData }}>
      <Child />
    </MyContext.Provider>
  );
};

const Child = () => {
  const { data, updateData } = useContext(MyContext);

  const handleButtonClick = () => {
    updateData('new data');
  };

  return (
    <div>
      <p>{data}</p>
      <button onClick={handleButtonClick}>Update Data</button>
    </div>
  );
};

In this example, we have a Parent component that provides the data and the updateData function to its child component, Child. The updateData function can be called to update the data value in the context.

In the Child component, we use the useContext hook to access the data and updateData values from the context. We also define a handleButtonClick function that updates the data value by calling the updateData function.

Now, whenever the Update Data button is clicked, the data value in the context will be updated, and any component that consumes that data will be re-rendered with the new value.

Note that if the context is updated frequently, it might be better to use a state management library like Redux instead. React Context is best suited for passing data down the component tree that doesn’t change frequently.

That’s it for this tutorial I hope you have got the idea of the context in React and why we use it. If you want to know more refer to it’s original documentation. Context – React (reactjs.org)

Happy Learning!

Leave a Comment