Context Hook in React

Cover image

Want to directly pass data to a deep-nested component using hooks? UseContext is here to help you! 👌

Let's have a look at how you can use the UseContext hook to share data between your components.

Create Context

First, let's start by creating a context to store some data. Let's assume we will be dealing with blog posts data..

// contexts/PostsContexts
import { createContext } from 'react';

export const PostsContext = createContext(null); // Context initial value is set to `null`

export default PostsContext;

At this point you have your context created.

The next step is to provide the context to a component.

Provide Context

We will provide the context to a component with the highest level we would like the data to be available.

In this case, we will provide the context to the App.js component.

This way, the data will be available for all the components under the App.js component. 👇

// App.js
import React from 'react';
import PostsContexts from './contexts/PostsContexts'; // Created Context earlier

function App() {
  const posts = [
      userId: 1,
      id: 1,
      title: 'The best title',
      body: 'Amazing body...'

  return <PostsContexts.Provider value={posts}>{/*
       Here goes the children components....

export default App;

Now we should have the posts data available from the App.js downwards in the component-tree.

Use Context Data

The final step is to read the blog post data in some other component. 🔥

Here is how you can do that from another nested component...

// components/NestedComponentWithContext.js
import React, { useContext } from 'react';
import PostsList from './PostsList';
import PostsContexts from '../contexts/PostsContexts';

function NestedComponentWithContext() {
  const posts = useContext(PostsContexts); // Gets the context data
  return <PostsList data={posts} />;

export default NestedComponentWithContext;

👉 Note - Since App.js is where the context was provided. NestedComponentWithContext must be initialized somewhere underneath App.js.

Now you know how to use UseContext! 🙌

Support us

Enjoyed the article? Share the summary thread on twitter.

Author image

Learn how to build scalable, fast and accessible web applications.

Follow us on Twitter