DEV Community

Cover image for What is useContext() in React?
Olena Drugalya
Olena Drugalya

Posted on • Updated on

What is useContext() in React?

In my previous blog about contextType I explained that we use contextType only in class-based components.
This post will explain useContext() hook, which is used only in function components.
If you’re new to hooks, you might want to check out the overview first on the official React docs page.

What is useContext()?

React provides the above hook for functional components to get access to context without Context.Consumer component. To understand better, lets remember how we use Consumer in functional components:

import React from 'react';
import MyContext from './MyContext';

const Person = () => {
   return(
     <PersonContainer>
       <MyContext.Consumer>
         {context => context.authenticated ? 
            <p>Authenticated!</p> : <p>Please log in</p>
         }
       </MyContext.Consumer>
     </PersonContainer>
   )
}
Enter fullscreen mode Exit fullscreen mode

To start using the hook, first we need to import useContext() to our project file to be able to use it:

import {useContext} from 'react';
Enter fullscreen mode Exit fullscreen mode

Now we can use it anywhere in our file. To do that we need to create a variable which will store our context data:

const myContext = useContext(MyContext);
Enter fullscreen mode Exit fullscreen mode

NOTE: When the nearest above the component updates, this hook will trigger a re-render with the latest context value passed to that provider.

Having context data stored now, we can log it for example:

console.log(myContext);
Enter fullscreen mode Exit fullscreen mode

AND of course we can use it instead of MyContext.Consumer:

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

const Person = () => {
   return(
     <PersonContainer>
         {myContext.authenticated ? 
            <p>Authenticated!</p> : <p>Please log in</p>
         }
     </PersonContainer>
   )
}
Enter fullscreen mode Exit fullscreen mode

Summary:
1.) useContext() hook is used to get context data and use it anywhere in the file
2.) it can be used only in functional components
3.) it will trigger a re-render with the latest context value passed to the context provider.

If you like to read my blog, you can buy me coffee! :)

Top comments (0)