Contents of React Interview Questions

Comprehensive collection of React interview questions and answers covering hooks, components, state management, and best practices.

How to use Context API with Hooks?

The Context API allows you to share data across components without passing props manually at every level. With Hooks (useContext), it's very simple to use:

Step 1: Create a context

import { createContext } from 'react'; const ThemeContext = createContext('light');

Step 2: Provide a value using a Provider

<ThemeContext.Provider value="dark"> <MyComponent /> </ThemeContext.Provider>

Step 3: Consume the context using useContext

import { useContext } from 'react'; function MyComponent() { const theme = useContext(ThemeContext); return <div>Current theme: {theme}</div>; }

✅ No need for a Consumer component — useContext gives direct access to the context value.