Basic Hooks in React - useContext()

Subscribe to my newsletter and never miss my upcoming articles

This blog post continues the series about React Hooks.

Here we are exploring one of basic and important hooks in React - useContext().

What is useContext()?

useContext() is JavaScript function, which lets you read the context and subscribe to its changes in functional component.

If you are not familiar with React Context object, I suggest you to read about Context API first before you proceed further with the article.

How and when use useContext()

To use this hook, you need to import it first from React library like this:

import {useContext} from 'react';

You can use this hook without import as well like this - React.useContext(), for me it's just more convenient to import and destructure first this function and then use it when need in the code.

Than we call useContext() function, which accepts context object as argument and returns current context value:

const contextValue = useContext(MyContext);

The context object should be created above the useContext() hook before the hook is called (or imported from another file).

We use useContext() in functional component the same way as we would use Context API, except that the hook works with a MyContext.Provider and MyContext.Consumer component in one call.

Let's consider we are building app where we have a button and by clicking on it the status of authentication is changed from Yes to No.

First we need to create Context:

// Creating the context object and passing the default values. 

export const authContext = React.createContext({status:null,login:()=>{}});

Now we import Context to our file and use it's values anywhere we find it necessary:

import {AuthContext} from './authContext';
import {useContext} from 'react';

export const Auth = () =>{

const auth = useContext(AuthContext); 

return ( 
    <> 
      <h1>Are you authenticated?</h1> 
      {auth.status ?  <p>Yes you are</p> :  <p>No you are not</p> 
} 
      <button onClick={auth.login}>Click To Login</button> 
    </> 
  ); 
}

Conclusion

The React hook useContext() provides you with a functionality to avoid props drilling in the components tree and use Context object in functional component in one call.

Thank you for reading my blog. Feel free to connect on LinkedIn or Twitter :)

Buy Me a Coffee at ko-fi.com

No Comments Yet