Subscribe
Using the useContext hook in React: Sharing data between components
5 mins read

By: vishwesh

Using the useContext hook in React: Sharing data between components

React is a popular JavaScript library for building user interfaces. It provides a simple and efficient way to create reusable components that can be easily combined to create complex UIs. One of the key features of React is its ability to manage state within components, making it easy to keep track of changes in the UI and update the underlying data.

However, managing state across multiple components can quickly become complex, especially as the number of components grows. In order to simplify the process of sharing data between components, React provides the useContext hook.

In this article, we'll explore how to use the useContext hook to share data between components in a React application. We'll start by explaining what the useContext hook is and how it works, and then we'll walk through an example of using it in a functional component.

What is the useContext Hook?

The useContext hook is a built-in hook in React that allows you to consume data from a React context in a functional component. A context is a way to pass data down the component tree without having to manually pass props down each level.

The useContext hook works by taking a context object as its argument and returning the current value of that context. It's important to note that the useContext hook can only be used within a functional component.

How to Use the useContext Hook

To use the useContext hook, you'll first need to create a context object. This object can be created using the createContext() method, which is built-in to React.

import React, { createContext } from 'react';

const MyContext = createContext();

In this example, we've created a context object called MyContext using the createContext() method. This context object can be used to store data that will be shared across multiple components.

Next, you'll need to provide a value for the context object. This is done using the Provider component, which is also built-in to React.

<MyContext.Provider value={{ data: 'Hello World' }}>
  <App />
</MyContext.Provider>

In this example, we've wrapped the <App /> component with the <MyContext.Provider> component and provided a value for the context object. The value we've provided is an object with a single key-value pair, where the key is data and the value is 'Hello World'.

Now that we've created and provided a value for our context object, we can consume the data in a functional component using the useContext hook.

import React, { useContext } from 'react';

const MyComponent = () => {
  const { data } = useContext(MyContext);

  return (
    <div>
      <p>{data}</p>
    </div>
  );
};

In this example, we've created a functional component called MyComponent. Within the component, we're using the useContext hook to consume the data from the MyContext context object. We're then rendering the data within a <p> tag.

Example: Using the useContext Hook to Share Data Between Components

Let's walk through an example of using the useContext hook to share data between two components in a React application.

In this example, we'll create a simple counter application that consists of two components: a counter component and a display component. The counter component will allow the user to increment or decrement a counter value, and the display component will display the current value of the counter.

First, let's create a context object that will store the counter value.

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

const CounterContext = createContext();

const CounterProvider = ({ children }) => {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  const decrement = () => {
    setCount(count - 1);
  };

  const value = {
    count,
    increment,
    decrement,
  };

  return (
    <CounterContext.Provider value={value}>
      {children}
    </CounterContext.Provider>
  );
};

export default CounterProvider;

In this code, we've created a CounterContext object using createContext() and defined a CounterProvider component that wraps its children with the context provider. The provider value includes the current count value, as well as the increment and decrement functions, which update the count state.

Now that we have our context and provider, let's create the Counter and Display components that will consume the context data.

import React, { useContext } from 'react';
import CounterContext from './CounterContext';

const Counter = () => {
  const { increment, decrement } = useContext(CounterContext);

  return (
    <div>
      <button onClick={increment}>+</button>
      <button onClick={decrement}>-</button>
    </div>
  );
};

export default Counter;
import React, { useContext } from 'react';
import CounterContext from './CounterContext';

const Display = () => {
  const { count } = useContext(CounterContext);

  return (
    <div>
      <p>Count: {count}</p>
    </div>
  );
};

export default Display;

In these components, we're using the useContext hook to consume the counter context data. In the Counter component, we're using the increment and decrement functions to update the count value. In the Display component, we're displaying the current count value.

Finally, we'll put everything together in our App component.

import React from 'react';
import CounterProvider from './CounterContext';
import Counter from './Counter';
import Display from './Display';

const App = () => {
  return (
    <CounterProvider>
      <Counter />
      <Display />
    </CounterProvider>
  );
};

export default App;

In the App component, we're wrapping our Counter and Display components with the CounterProvider component. This makes the counter context data available to both components.

Conclusion

The useContext hook is a powerful tool for sharing data between components in a React application. By creating a context and using the useContext hook, you can simplify the process of passing data down the component tree and make your code more modular and reusable. With this technique, you can create complex applications with multiple components that share data without sacrificing code readability or maintainability.

Recent posts

Don't miss the latest trends

    Popular Posts

    Popular Categories