πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Context API

React Architecture🟒 Free Lesson

Advertisement

Context API

Creating contexts, provider patterns, avoiding re-renders, and when to use context.

Overview

Context provides a way to pass data through the component tree without prop drilling.

Key Concepts

  • createContext β€” Creates a context object with a default value
  • Provider β€” Wraps components that need access to context
  • useContext β€” Consumes context in function components
  • Context Splitting β€” Separate providers for state and dispatch to optimize re-renders
  • When to Use β€” Theme, auth, locale, and other app-wide state

Code Examples

import { createContext, useContext, useReducer } from 'react';

const AuthContext = createContext(null);
const AuthDispatchContext = createContext(null);

function authReducer(state, action) {
  switch (action.type) {
    case 'LOGIN':
      return { user: action.payload, isAuthenticated: true };
    case 'LOGOUT':
      return { user: null, isAuthenticated: false };
    default:
      return state;
  }
}

export function AuthProvider({ children }) {
  const [state, dispatch] = useReducer(authReducer, {
    user: null,
    isAuthenticated: false
  });

  return (
    <AuthContext.Provider value={state}>
      <AuthDispatchContext.Provider value={dispatch}>
        {children}
      </AuthDispatchContext.Provider>
    </AuthContext.Provider>
  );
}

export function useAuth() {
  const context = useContext(AuthContext);
  if (!context) throw new Error('useAuth must be used within AuthProvider');
  return context;
}

Practice

Create an authentication context with login/logout functionality and protected routes.

⭐

Premium Content

Context API

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement