DEV Community

Sajin Joe J
Sajin Joe J

Posted on

React useContext Hook – Interview Questions and Answers

Q1. What is useContext in React?
useContext is a React Hook used to share data between components without passing props manually through every level of the component tree.

Example: We can share cart data, user information, theme, and authentication status using useContext.

Q2. Why do we use useContext?
We use useContext to avoid prop drilling and share data between multiple components easily.

For example, in an e-commerce application:

  • Header needs cart count.
  • Product page needs add-to-cart functionality.
  • Cart page needs cart items.
  • Checkout page needs order information. Instead of passing props through multiple components, we can use useContext.

Q3. How do you create a Context in React?
We use createContext() to create a context.

import { createContext } from "react";

export const UserContext = createContext();
Enter fullscreen mode Exit fullscreen mode

Q4. What is Context Provider?
A Provider makes context data available to components inside its tree.

<UserContext.Provider value="Sajin">
    <App />
</UserContext.Provider>
Enter fullscreen mode Exit fullscreen mode

Here, "Sajin" is the value shared with child components that read this context.

Q5. How do you consume Context?
We use the useContext() Hook.

import { useContext } from "react";
import { UserContext } from "./UserContext";

function Profile() {

    const user = useContext(UserContext);

    return <h1>Hello {user}</h1>;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)