useContext in ReactJs

dinesh priyantha
2 min readJul 8, 2024

--

useContext is a hook in React that allows you to access the context values directly in functional components. Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Here’s a step-by-step guide on how to use useContext:

1. Create a Context

First, you need to create a context using the createContext function from React.

import React, { createContext } from 'react';

const MyContext = createContext();

2. Provide the Context

Wrap your component tree with the context provider and pass the value you want to share through the context.

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

const MyContext = createContext();

const App = () => {
const [value, setValue] = useState("Hello, World!");

return (
<MyContext.Provider value={{ value, setValue }}>
<MyComponent />
</MyContext.Provider>
);
};

3. Consume the Context

In any child component, you can use the useContext hook to access the context value.

import React, { useContext } from 'react';
import { MyContext } from './App'; // Adjust the import path as necessary

const MyComponent = () => {
const { value, setValue } = useContext(MyContext);

return (
<div>
<p>{value}</p>
<button onClick={() => setValue("New Value!")}>Change Value</button>
</div>
);
};

Example

Here’s a complete example that brings everything together:

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

const MyContext = createContext();

const MyComponent = () => {
const { value, setValue } = useContext(MyContext);

return (
<div>
<p>{value}</p>
<button onClick={() => setValue("New Value!")}>Change Value</button>
</div>
);
};

const App = () => {
const [value, setValue] = useState("Hello, World!");

return (
<MyContext.Provider value={{ value, setValue }}>
<MyComponent />
</MyContext.Provider>
);
};

export default App;

When to Use useContext

useContext is particularly useful when:

  • You have data or functions that need to be accessed by many components at different nesting levels.
  • You want to avoid prop drilling (passing props through many layers of components).

However, use it judiciously as excessive use of context can lead to performance issues due to unnecessary re-renders of components that consume the context.

--

--