0% found this document useful (0 votes)
11 views

Document_useContext

Uploaded by

go.coronago
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Document_useContext

Uploaded by

go.coronago
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 3

UseContext hook:

1. What is it?

useContext is a React Hook that lets you read and subscribe to context from your component.

Syntax: const value = useContext(SomeContext)

The useContext hook is used to access data that has been passed down from a higher-level component.
It allows you to access data that is stored in the context object without having to manually pass it down
as props.

we need to use the Provider component to make the context data available to the components that
need it.

2. What is the real time scenario for this hook ?

when we wan't to share data across multiple components.

3. What benefit we get from it.

It can help reduce prop drilling and make your code more readable and maintainable.

4. When do I use it?

The useContext hook is best used when you need to share state or behavior between multiple
components that are not directly connected through the component hierarchy

5. How to use it??

import { useContext, createContext, useState } from "react";

export const MyContext = createContext();

export default function App() {

const [value, setValue] = useState(5);

return (

<>

<MyContext.Provider value={{ value, setValue }}>

<Child />
</MyContext.Provider>

</>

);

const Child = () => {

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

return (

<div>

{value}

<button onClick={() => setValue(value + 1)}>Increment</button>

</div>

);

};

Output:
Initial Render:

On Button Click:
drawback:

The useContext hook can cause unnecessary re-renders if not used correctly. When the context value
changes, all components that consume the context will re-render, even if they don't use the part of the
context that changed.

You might also like