This blog post introduces the useContext hook in React and explains how it helps eliminate prop drilling by providing a way to share state efficiently across components. Using a step-by-step approach, it demonstrates how to create and use a Context Provider in a simple MCQ Quiz Application, where answer visibility is managed globally. Key benefits, implementation details, and best practices for using useContext are covered, setting the stage for more advanced use cases in Part 2.

Understanding the useContext Hook in React (Part 1)

In modern React applications, managing state and passing data efficiently is crucial. One common challenge developers face is "prop drilling," where props are passed down multiple levels of components, making code harder to manage. React's useContext hook, along with the Context API, provides an elegant solution to this problem. In this blog post, we will explore the basics of the useContext hook and how it helps simplify state management in React applications.


What is the useContext Hook?

useContext is a built-in React hook that allows components to access values from a Context without needing to pass props manually at every level. It provides a way to share state across multiple components in a React application.

Key Benefits of useContext:

✔ Eliminates the need for prop drilling. ✔ Enhances code readability and maintainability. ✔ Allows for efficient state sharing between components. ✔ Works well with useState and other hooks.


Creating and Using Context in React

Let's understand how useContext works by building a simple MCQ Quiz Application where each question's answer visibility is managed independently using Context API and useContext.

Step 1: Create a Context

First, we create a context using React.createContext():

import React, { useState, useContext } from 'react';

const AnswerVisibilityContext = React.createContext();

This AnswerVisibilityContext will manage the state of whether an answer is visible or hidden.


Step 2: Create a Context Provider

A Context Provider component is responsible for managing and providing the state to its children components.

const AnswerVisibilityProvider = ({ children }) => {
  const [isAnswerVisible, setIsAnswerVisible] = useState(false);
  
  const toggleAnswerVisibility = () => {
    setIsAnswerVisible(prevState => !prevState);
  };

  return (
    <AnswerVisibilityContext.Provider value={{ isAnswerVisible, toggleAnswerVisibility }}>
      {children}
    </AnswerVisibilityContext.Provider>
  );
};

Explanation:

✔ We use useState to manage the visibility state (isAnswerVisible). ✔ The toggleAnswerVisibility function toggles the answer visibility. ✔ The AnswerVisibilityContext.Provider wraps the children components to provide them access to the state.


Step 3: Use Context in a Component

Now, we create a Question component that uses useContext to get access to the answer visibility state.

const Question = ({ question, options, answer }) => {
  const { isAnswerVisible, toggleAnswerVisibility } = useContext(AnswerVisibilityContext);

  return (
    <div>
      <h2>{question}</h2>
      <ul>
        {options.map((option, index) => (
          <li key={index}>{option}</li>
        ))}
      </ul>
      <button onClick={toggleAnswerVisibility}>
        {isAnswerVisible ? 'Hide Answer' : 'Show Answer'}
      </button>
      {isAnswerVisible && <p>Correct Answer: {answer}</p>}
    </div>
  );
};

How it Works:

useContext(AnswerVisibilityContext) gives access to isAnswerVisible and toggleAnswerVisibility. ✔ Clicking the button toggles the answer's visibility.


Step 4: Implementing the App Component

const App = () => {
  const questions = [
    { 
      question: '1. What is React?', 
      options: ['A library for building UI', 'A database', 'A server-side language', 'A CSS framework'], 
      answer: 'A library for building UI' 
    },
    { 
      question: '2. What is JSX?', 
      options: ['A syntax extension for JavaScript', 'A type of CSS', 'A database query language', 'A server framework'], 
      answer: 'A syntax extension for JavaScript' 
    }
  ];

  return (
    <AnswerVisibilityProvider>
      <div>
        <h1>MCQ Questions</h1>
        {questions.map((q, index) => (
          <Question key={index} question={q.question} options={q.options} answer={q.answer} />
        ))}
      </div>
    </AnswerVisibilityProvider>
  );
};

export default App;

Why Use a Single Provider Instead of Multiple Instances?

✔ Placing the AnswerVisibilityProvider at a higher level ensures all questions share the same state. ✔ This allows for global control over answer visibility, making toggling more efficient.


Conclusion

In this blog post, we explored the useContext hook in React and how it simplifies state management by eliminating prop drilling. We created an MCQ Quiz Application where all questions share a single context for answer visibility using the Context API and useContext.

Key Takeaways:

useContext allows components to access shared state without prop drilling. ✔ The Context Provider manages state and provides it to child components. ✔ Placing the Provider at the correct level determines whether state is shared or independent. ✔ The combination of useContext and useState makes state management in React easier.

Stay tuned for Part 2, where we will explore advanced use cases of useContext, including integrating it with complex state logic, performance optimizations, and best practices.

To Know more visit our YOUTUBE channel


Happy Coding! 🚀

MCQs on useContext Hook in React
1. What problem does the useContext hook help solve in React?
a) Slow rendering of components
b) Prop drilling issue
c) Lack of styling in components
d) Inability to use state in functional components

2. Which React method is used to create a new context?
a) React.useContext()
b) React.createContext()
c) React.createProvider()
d) React.useState()

3. What is the main function of a Context Provider in React?
a) It creates a new state variable for a component
b) It provides a way to fetch data from an API
c) It manages and provides shared state to child components
d) It defines how components should render on the screen

4. Which hook is used inside a child component to access the value from a context?
a) useState
b) useEffect
c) useContext
d) useRef

5. In the MCQ Quiz Application, what does the toggleAnswerVisibility function do?
a) Changes the question text
b) Hides or shows the correct answer
c) Selects the correct answer automatically
d) Navigates to the next question

6. What is a key advantage of using useContext over passing props manually?
a) It eliminates the need for Redux
b) It allows using class components
c) It removes the complexity of prop drilling
d) It prevents the use of state in React components

7. Where should the Context Provider be placed in the component tree?
a) At the root level of the application
b) Inside each individual component
c) Inside the useEffect hook
d) Inside a callback function

8. What will happen if multiple instances of a Context Provider are created?
a) They will share the same state
b) They will have independent state values
c) It will cause a React error
d) The application will not render

9. In the Question component, how do we access the shared state from the context?
a) useContext(AnswerVisibilityContext)
b) useState(AnswerVisibilityContext)
c) useEffect(AnswerVisibilityContext)
d) useReducer(AnswerVisibilityContext)

10. What is the expected topic of Part 2 of this blog series?
a) React component styling techniques
b) Advanced use cases of useContext
c) Introduction to Redux
d) Building a React application without state management

Answers
1. b) Prop drilling issue
2.  b) React.createContext()
3. c) It manages and provides shared state to child components
3. c) useContext
4. b) Hides or shows the correct answer
5. c) It removes the complexity of prop drilling
6. a) At the root level of the application
7. b) They will have independent state values
8. a) useContext(AnswerVisibilityContext)
10. b) Advanced use cases of useContext
 

Download Lecture Pdf..

Leave a Comment

Get a Call Back from Our Career Assistance Team Request Callback
WhatsApp