Lecture Notes Of Day 13 - useContext Hook

Rashmi Mishra
0

Lecture Notes Of  Day 13 - useContext Hook


Objective

To understand the useContext hook for global state management in React.

Expected Outcome

Students will be able to share data across multiple components without prop drilling by using React Context.


Introduction

React applications often have deeply nested components that need to share data. This can lead to prop drilling, where props are passed down multiple levels unnecessarily. To solve this, React provides Context and the useContext hook.


Key Concepts

What is Context?

  • Context provides a way to share values (data) like state, themes, or functions globally between components without explicitly passing them down as props.

What is useContext?

  • The useContext hook simplifies accessing the context value in functional components.

Advantages of useContext

1.  Avoids Prop Drilling: No need to pass props down manually at every level.

2.  Global State Management: Easy to share common data like themes, user authentication, or language preferences.

3.  Simplifies Code: Reduces the complexity of component trees.


Steps to Use useContext

1.  Create a Context

o    Use React.createContext() to create a context.

2.  Provide Context Value

o    Wrap the parent component with a Context Provider and pass the data as a value.

3.  Consume Context Value

o    Use the useContext hook to access the data in child components.


Practical Example

1. Setting Up Context

jsx

Copy code

import React, { createContext, useState } from "react";

 

// Create a Context

export const UserContext = createContext();

 

const UserProvider = ({ children }) => {

  const [user, setUser] = useState("John Doe");

 

  return (

    <UserContext.Provider value={{ user, setUser }}>

      {children}

    </UserContext.Provider>

  );

};

 

export default UserProvider;

2. Wrapping the Application

Wrap your application with the context provider in the root component:

jsx

Copy code

import React from "react";

import ReactDOM from "react-dom";

import App from "./App";

import UserProvider from "./UserContext";

 

ReactDOM.render(

  <UserProvider>

    <App />

  </UserProvider>,

  document.getElementById("root")

);

3. Consuming Context with useContext

In child components, use the useContext hook to access the context value:

jsx

Copy code

import React, { useContext } from "react";

import { UserContext } from "./UserContext";

 

const UserProfile = () => {

  const { user, setUser } = useContext(UserContext);

 

  return (

    <div>

      <h1>Welcome, {user}!</h1>

      <button onClick={() => setUser("Jane Doe")}>Change User</button>

    </div>

  );

};

 

export default UserProfile;


Explanation of the Example

1.  Creating Context:

o    UserContext is created with createContext.

o    It stores the state (user) and the function to update it (setUser).

2.  Providing Context:

o    UserProvider wraps the application and provides user and setUser globally.

3.  Consuming Context:

o    useContext(UserContext) allows the UserProfile component to access user and setUser.


Benefits of This Approach

  • UserProfile does not depend on intermediate components to receive the user value or the setUser function.
  • Adding or removing components in the middle does not affect data flow.

Common Use Cases of useContext

1.  Theme Management: Dark mode vs. light mode.

2.  User Authentication: Sharing user details across the app.

3.  Language Preferences: Multi-language support.

4.  Global Settings: App-wide configurations like API endpoints.


Exercise

1. Create Your Own Context

  • Build a context to manage a theme (light/dark mode).

2. Enhance the Example

  • Add another component to show how data can flow without prop drilling.

Conclusion

  • The useContext hook simplifies global state management by eliminating prop drilling.
  • It is a lightweight solution for sharing data across components in small to medium-sized React applications.
  • For larger applications, consider combining it with state management libraries like Redux.
Tags

Post a Comment

0Comments

Post a Comment (0)