Context provides a way to pass data through the component tree without props drilling.
Getting Started
What is React?
Components & Props
Components & Props
Performance & Testing
React.memo & Lazy Loading
Custom Hooks
Building Custom Hooks
Error Boundaries
Error Handling
Server Components
React Server Components
Next.js Introduction
Next.js Basics
Animations & Transitions
Framer Motion
React
Intermediate
FREE
Context API
Lesson 1 of 17
Intermediate
Interactive
Syntax
REACT
const AuthContext = createContext(null); function AuthProvider({ children }) { const [user, setUser] = useState(null); return ( <AuthContext.Provider value={{ user, setUser }}> {children} </AuthContext.Provider> ); }
Context API
REACT
import { createContext, useContext, useState } from "react"; const AuthContext = createContext(null); function AuthProvider({ children }) { const [user, setUser] = useState(null); const login = (userData) => setUser(userData); const logout = () => setUser(null); return ( <AuthContext.Provider value={{ user, login, logout }}> {children} </AuthContext.Provider> ); } function useAuth() { return useContext(AuthContext); }