DEV Community

Dinesh G
Dinesh G

Posted on

UseContext in React JS

What is useContext

The useContext hook in React provides a way to consume values from a React Context within functional components. It is a powerful tool for sharing data across the component tree without the need for "prop drilling," where props are manually passed down through multiple levels of nested components.

useContext

In React, context is more like a global variable that can be used across all components in an application. An example of when to use the context hook is to set the preferred theme or to store the currently signed-in user.

You should use the context hook only when you need some data to be accessible by many components.

working with useContext

To understanduseContext better we'll be creating a context that stores a user's details and we'll be showing some things to the user if their details are stored in the context.

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

const UserContext = createContext(); 

const UserProvider = (props) => {
    const [username, setUsername] = useState('');
// the state that we'll be storing the username into

/* because we will be providing an object to the provider, it is better to put the value inside a useMemo so that the component will only re-render when there's a change in the value. */

const value = useMemo(
   () => ({username, setUsername}),[username])


    return (
        <UserContext.Provider
            value={value}
        >
            {props.children}
        </UserContext.Provider>
    );
}
export { UserContext, UserProvider };

Enter fullscreen mode Exit fullscreen mode

HAPPY CODING...

Top comments (0)