Document_useContext
Document_useContext
1. What is it?
useContext is a React Hook that lets you read and subscribe to context from your component.
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.
It can help reduce prop drilling and make your code more readable and maintainable.
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
return (
<>
<Child />
</MyContext.Provider>
</>
);
return (
<div>
{value}
</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.