Lecture on Context API and Theme Switcher in React

Jul 13, 2024

Lecture on Context API and Theme Switcher in React

Introduction

  • Informal teaching style.
  • Target for the video: 1000 comments.
  • Topic: Context API and its relevance to React.
  • Challenges because of the complexity of the topic.

Fundamentals of Context API

  1. Starting Point: Props

    • Understanding Props and Prop drilling issues.
    • Context API is introduced after understanding Prop issues.
    • Further evolves into Redux, Redux Toolkit, Zustand.
  2. Context API Essentials

    • Global state management without Prop drilling.
    • Typical structure involves creating Context, Provider, and using useContext.
    • Context API can solve prop drilling by creating a central store that provides data to the entire React component tree.
    • Context setup includes createContext, Provider, and value passing.
    • Example use-case involves passing a global user state (username etc.) across components like Dashboard, Card, etc.

Practical Implementation: Context API

  1. Steps to Implement Context API

    • Create a context using createContext.
    • Create a Provider to wrap components and provide data access.
    • Use the useContext hook to access context data within components.
  2. Example Code Analysis

    • Created UserContext and UserContextProvider to manage user state globally.
      import { createContext, useState } from 'react';
      
      const UserContext = createContext();
      
      const UserContextProvider = ({ children }) => {
        const [user, setUser] = useState(null);
        return (
          <UserContext.Provider value={{ user, setUser }}>
            {children}
          </UserContext.Provider>
        );
      };
      
      export { UserContext, UserContextProvider };
      
  3. Component Structure

    • App.jsx wrapped with UserContextProvider.
    • Separate components for Login and Profile which consume context data.
    • Example Login Component to set user:
      import { useContext, useState } from 'react';
      import { UserContext } from './UserContext';
      
      const Login = () => {
        const [username, setUsername] = useState('');
        const { setUser } = useContext(UserContext);
      
        const handleSubmit = (event) => {
          event.preventDefault();
          setUser({ username });
        };
      
        return (
          <form onSubmit={handleSubmit}>
            <input type="text" value={username} onChange={(e) => setUsername(e.target.value)} />
            <button type="submit">Login</button>
          </form>
        );
      };
      
      export default Login;
      
  4. Profile Component

    • Consume the user state:
      import { useContext } from 'react';
      import { UserContext } from './UserContext';
      
      const Profile = () => {
        const { user } = useContext(UserContext);
        return user ? <div>Welcome, {user.username}</div> : <div>Please login</div>;
      };
      
      export default Profile;
      

Advanced Use-Case: Theme Switcher

  1. Theme Context Setup

    • Similar to User Context but includes light and dark mode management.
      import { createContext, useState, useContext } from 'react';
      
      const ThemeContext = createContext();
      
      const ThemeProvider = ({ children }) => {
        const [themeMode, setThemeMode] = useState('light');
      
        const toggleTheme = () => {
          setThemeMode((prevMode) => (prevMode === 'light' ? 'dark' : 'light'));
        };
      
        return (
          <ThemeContext.Provider value={{ themeMode, toggleTheme }}>
            {children}
          </ThemeContext.Provider>
        );
      };
      
      export { ThemeContext, ThemeProvider };
      
  2. Theme Application

    • Apply theme mode using useEffect to toggle classes on the HTML element.
    • Tailwind CSS usage for conditional class application based on the theme.
  3. Theme Button Component

    • Button to toggle between themes using ThemeContext:
      import { useContext } from 'react';
      import { ThemeContext } from './ThemeContext';
      
      const ThemeButton = () => {
        const { themeMode, toggleTheme } = useContext(ThemeContext);
      
        return (
          <button onClick={toggleTheme}>
            Switch to {themeMode === 'light' ? 'dark' : 'light'} mode
          </button>
        );
      };
      
      export default ThemeButton;
      
  4. Tailwind Configuration Adjustment

    • Remember to add and configure Tailwind for dark mode.
      darkMode: 'class',
      
  5. Complete Project Structure

    • Use ThemeProvider and components properly.

Conclusion

  • Context API simplifies state management in React applications.
  • Helps prevent prop drilling and maintains clean code structure.
  • Works well with libraries like Tailwind CSS for theme management.
  • Practicing the implementation consolidates understanding.