0%
State Management in React

State Management

Managing global data

10-15 min

State Management in React

State management is a crucial aspect of React applications. We'll explore different approaches to managing your application's global state.

Context API

Creating a context

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

const ThemeContext = createContext();

function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('light');

  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

// Custom hook to use the context
function useTheme() {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme doit être utilisé dans un ThemeProvider');
  }
  return context;
}

Using the context

function App() {
  return (
    <ThemeProvider>
      <Navigation />
      <MainContent />
    </ThemeProvider>
  );
}

function ThemeToggle() {
  const { theme, setTheme } = useTheme();

  return (
    <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
      Changer le thème
    </button>
  );
}

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!