DEV Community

Deva I
Deva I

Posted on

UseContext

Definition of UseContext:

✓ The useContext Hook in React allows functional components to access shared data without "prop drilling"—the tedious process of passing props through every level of a component tree.

✓ It is primarily used for global-like data such as user authentication, themes, or language settings.

How to use useContext :

  1. Create Context: Use createContext() to define a context object. You can provide a default value.

  2. Provide Context: Wrap your component tree with a and pass the data into its value prop. All nested components can now access this data.

  3. Consume Context: Inside a functional component, call useContext(MyContext) to retrieve the current value.

When to Use It :

Global Settings: Themes (dark/light mode), language preferences, or user authentication status.

Deep Nesting: When data is needed by many components at different levels of the tree.

Top comments (0)