ЁЯзСтАНЁЯПл

Context API and Theme Management in React

Jun 22, 2024

Lecture Notes: Context API and Theme Management in React

Introduction

  • Informal teaching style, aim for interactive session
  • Target: 1000 comments
  • Topic: Context API
  • Importance: Difficult topic, crucial for React developers

Overview

  • Common mistakes: Starting directly with documentation
  • Proper start: From Props, understanding the problem of Props
  • Context API helps with Props drilling issue

Personal Anecdotes

  • Teaching experience with multiple institutions and companies
  • Importance of proper context understanding in React

Project Overview

  • We're building a Theme Switcher App
  • Two projects: For seeing different coding styles
  • Need for a project to deeply understand Context API

Basic Project Setup

  • React Components: App, Card, Theme Button
  • Initial Setup: Basic App.js with minimal code

Context API Basics

  • Import React
  • Create Context: createContext
  • Export the context
  • Context provides variables on a global scale

Creating Context

  • File Structure: Context/UserContext.js
  • Code: import React, { createContext } from 'react'; const UserContext = createContext(); export default UserContext;

Creating Provider

  • File Structure: Context/UserProvider.js
  • Code: import React, { useState } from 'react'; import UserContext from './UserContext'; const UserProvider = ({ children }) => { const [user, setUser] = useState(null); return ( <UserContext.Provider value={{ user, setUser }}> {children} </UserContext.Provider> ); }; export default UserProvider;

Using Context

  • Wrapping App component import UserProvider from './Context/UserProvider'; const App = () => ( <UserProvider> {/* Rest of your component */} </UserProvider> );

Creating Components

  • Login Component import React, { useState, useContext } from 'react'; import UserContext from '../Context/UserContext'; const Login = () => { const { setUser } = useContext(UserContext); const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); // Handle Submit const onSubmit = (e) => { e.preventDefault(); setUser({ username, password }); }; // Component JSX return ( <form onSubmit={onSubmit}> <input type="text" value={username} onChange={(e) => setUsername(e.target.value)} placeholder="Username" /> <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Password" /> <button type="submit">Submit</button> </form> ); }; export default Login;
  • Profile Component: Display state from context import React, { useContext } from 'react'; import UserContext from '../Context/UserContext'; const Profile = () => { const { user } = useContext(UserContext); if (!user) return <p>Please log in</p>; return <div>Welcome, {user.username}</div>; }; export default Profile;

Advanced Context API Example: Theme Management

  • Theme Context Creation
    • Single file for creating context and provider
    import React, { createContext, useState, useContext, useEffect } from 'react'; const ThemeContext = createContext(); export const ThemeProvider = ({ children }) => { const [theme, setTheme] = useState('light'); const toggleTheme = () => setTheme(theme === 'light' ? 'dark' : 'light'); useEffect(() => { document.documentElement.classList.remove('light', 'dark'); document.documentElement.classList.add(theme); }, [theme]); return ( <ThemeContext.Provider value={{ theme, toggleTheme }}> {children} </ThemeContext.Provider> ); }; export const useTheme = () => useContext(ThemeContext);

Theme Button Component

  • Code: import React from 'react'; import { useTheme } from '../Context/ThemeContext'; const ThemeButton = () => { const { theme, toggleTheme } = useTheme(); return ( <button onClick={toggleTheme}> Switch to {theme === 'light' ? 'dark' : 'light'} mode </button> ); }; export default ThemeButton;

Card Component

  • Using current theme in styling

Integration in App Component

  • Incorporate ThemeProvider and components: import React from 'react'; import { ThemeProvider } from './Context/ThemeContext'; import ThemeButton from './Components/ThemeButton'; import Card from './Components/Card'; const App = () => ( <ThemeProvider> <ThemeButton /> <Card /> </ThemeProvider> );

Conclusion

  • Summary of Context API importance
  • How themes work with Context API
  • Importance of understanding Context for large-scale React applications