useContext in React provides a way to pass data from parent to child component without using props.
import { createContext } from "react";
const MyContext = createContext();
export default MyContext;
const Parent = () => {
const contextValue = "Hello from Context!";
return (
<MyContext.Provider value={contextValue}>
{/* Your component tree */}
<Child />
</MyContext.Provider>
);
};
export default Parent;
const Child = () => {
const contextValue = useContext(MyContext);
return <p>{contextValue}</p>;
// return (
// <MyContext.Consumer>
// {(contextValue) => <div>{contextValue}</div>}
// </MyContext.Consumer>
// );
};
export default Child;
-
The createContext() function returns an object with Provider and Consumer properties.
-
The Provider property is responsible for providing the context value to all its child components.
-
The useContext() method or Consumer property can be used to consume the context value in child components.
Use useContext instead of props when you want to avoid prop drilling
and access context values directly within deeply nested components.
Feature | Description |
---|---|
Theme Switching (Dark/Light) | Centralize and pass theme selection from parent to all child components. |
Localization (Language Selection) | Centralize and pass language selection from parent to all child components. |
Centralize Configuration Settings | Centralize common settings like API endpoints. Changes in parent affect all children. |
User Preferences | Centralize user preferences beyond theme and localization. |
Notification System | Access notification state from context for components triggering or displaying notifications. |