Kurs JavaScript i React · Moduł 4: Context API i useReducer

Globalne zarządzanie stanem

12 min czytania ·
W tej lekcji9

Wraz z rozwojem aplikacji React, zarządzanie stanem staje się coraz bardziej złożonym wyzwaniem. W małych aplikacjach, lokalny stan komponentów i props są wystarczające, ale w miarę skalowania, potrzebujemy bardziej zaawansowanych rozwiązań do zarządzania globalnym stanem aplikacji.

W tym module przyjrzymy się różnym podejściom do globalnego zarządzania stanem w React, od wbudowanych mechanizmów po popularne biblioteki zewnętrzne.

Wyzwania związane z globalnym stanem

Zanim zagłębimy się w rozwiązania, zrozummy dlaczego zarządzanie globalnym stanem może być wyzwaniem:

  1. Współdzielenie danych - komponenty w różnych częściach drzewa komponentów mogą potrzebować dostępu do tych samych danych
  2. Synchronizacja - zmiany w jednym miejscu powinny być widoczne wszędzie, gdzie dane są używane
  3. Przewidywalność - aktualizacje stanu powinny być przewidywalne i łatwe do śledzenia
  4. Wydajność - niepotrzebne renderowanie powinno być minimalizowane
  5. Złożoność - logika stanu może być skomplikowana, z wieloma powiązanymi zmianami

Context API + useReducer jako podstawowe rozwiązanie

Jak poznaliśmy w poprzednich modułach, połączenie Context API z useReducer zapewnia solidne podstawy do globalnego zarządzania stanem:

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

// Początkowy stan
const initialState = {
  missions: [],
  activeMission: null,
  user: null,
  isLoading: false,
  error: null
};

// Reducer
function appReducer(state, action) {
  switch (action.type) {
    case 'LOGIN_SUCCESS':
      return { ...state, user: action.payload, error: null };
    case 'LOGOUT':
      return { ...state, user: null };
    case 'FETCH_MISSIONS_START':
      return { ...state, isLoading: true };
    case 'FETCH_MISSIONS_SUCCESS':
      return { ...state, missions: action.payload, isLoading: false };
    case 'FETCH_MISSIONS_ERROR':
      return { ...state, error: action.payload, isLoading: false };
    case 'SET_ACTIVE_MISSION':
      return { ...state, activeMission: action.payload };
    default:
      return state;
  }
}

// Kontekst
const AppStateContext = createContext();

// Provider
function AppStateProvider({ children }) {
  const [state, dispatch] = useReducer(appReducer, initialState);

  // Możemy także dodać funkcje pomocnicze
  const login = async (credentials) => {
    try {
      dispatch({ type: 'LOGIN_START' });
      // API call do logowania
      const user = await authService.login(credentials);
      dispatch({ type: 'LOGIN_SUCCESS', payload: user });
    } catch (error) {
      dispatch({ type: 'LOGIN_ERROR', payload: error.message });
    }
  };

  const fetchMissions = async () => {
    try {
      dispatch({ type: 'FETCH_MISSIONS_START' });
      const missions = await missionService.getAll();
      dispatch({ type: 'FETCH_MISSIONS_SUCCESS', payload: missions });
    } catch (error) {
      dispatch({ type: 'FETCH_MISSIONS_ERROR', payload: error.message });
    }
  };

  // Wartość kontekstu
  const value = {
    state,
    dispatch,
    login,
    fetchMissions,
    setActiveMission: (mission) => dispatch({ type: 'SET_ACTIVE_MISSION', payload: mission })
  };

  return (
    <AppStateContext.Provider value={value}>
      {children}
    </AppStateContext.Provider>
  );
}

// Hook do korzystania z kontekstu
function useAppState() {
  const context = useContext(AppStateContext);
  if (context === undefined) {
    throw new Error('useAppState must be used within an AppStateProvider');
  }
  return context;
}

// Użycie w aplikacji
function App() {
  return (
    <AppStateProvider>
      <Header />
      <Main />
      <Footer />
    </AppStateProvider>
  );
}

function Header() {
  const { state, dispatch } = useAppState();

  return (
    <header>
      {state.user ? (
        <>
          <span>Witaj, {state.user.name}</span>
          <button onClick={() => dispatch({ type: 'LOGOUT' })}>Wyloguj</button>
        </>
      ) : (
        <LoginButton />
      )}
    </header>
  );
}

function MissionsList() {
  const { state, fetchMissions, setActiveMission } = useAppState();

  useEffect(() => {
    fetchMissions();
  }, []);

  if (state.isLoading) return <p>Ładowanie misji...</p>;
  if (state.error) return <p>Błąd: {state.error}</p>;

  return (
    <div>
      <h2>Dostępne misje</h2>
      <ul>
        {state.missions.map(mission => (
          <li key={mission.id}>
            {mission.name}
            <button onClick={() => setActiveMission(mission)}>
              Wybierz
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
}

To rozwiązanie ma kilka zalet:

  • Używa wbudowanych mechanizmów React
  • Nie wymaga zewnętrznych zależności
  • Daje dobre podstawy strukturalne dla globalnego stanu

Jednakże w miarę jak aplikacja rośnie, to rozwiązanie może napotykać ograniczenia związane z wydajnością i organizacją kodu.

Skalowanie aplikacji z wieloma kontekstami

Dla większych aplikacji zaleca się podział globalnego stanu na mniejsze, niezależne konteksty według domen:

// Kontekst autentykacji
const AuthContext = createContext();

function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  const login = async (credentials) => {
    setIsLoading(true);
    try {
      const user = await authService.login(credentials);
      setUser(user);
      setError(null);
    } catch (err) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  };

  const logout = async () => {
    await authService.logout();
    setUser(null);
  };

  return (
    <AuthContext.Provider value={{ user, isLoading, error, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
}

// Kontekst misji
const MissionsContext = createContext();

function MissionsProvider({ children }) {
  const [missions, setMissions] = useReducer(missionsReducer, []);
  const [activeMission, setActiveMission] = useState(null);
  // reszta logiki...

  return (
    <MissionsContext.Provider value={{ missions, activeMission, /*...*/ }}>
      {children}
    </MissionsContext.Provider>
  );
}

// Kontekst UI
const UIContext = createContext();

function UIProvider({ children }) {
  const [darkMode, setDarkMode] = useState(false);
  const [sidebarOpen, setSidebarOpen] = useState(true);
  // reszta logiki...

  return (
    <UIContext.Provider value={{ darkMode, toggleDarkMode: () => setDarkMode(!darkMode), /*...*/ }}>
      {children}
    </UIContext.Provider>
  );
}

// Łączenie wszystkich providerów
function AppProviders({ children }) {
  return (
    <AuthProvider>
      <MissionsProvider>
        <UIProvider>
          {children}
        </UIProvider>
      </MissionsProvider>
    </AuthProvider>
  );
}

Zalety tego podejścia:

  • Lepszy podział odpowiedzialności
  • Mniejsze konteksty = mniej niepotrzebnych renderowań
  • Łatwiejsze testowanie poszczególnych modułów
  • Komponenty mogą korzystać tylko z potrzebnych kontekstów

Optymalizacja wydajności z useMemo i memo

Jednym z wyzwań przy używaniu Context API jest wydajność - każda zmiana wartości kontekstu powoduje przerenderowanie wszystkich komponentów, które używają tego kontekstu. Oto kilka technik optymalizacji:

function OptimizedProvider({ children }) {
  const [state, dispatch] = useReducer(reducer, initialState);

  // Memizacja wartości kontekstu
  const contextValue = useMemo(() => {
    return { state, dispatch };
  }, [state, dispatch]);

  return (
    <AppContext.Provider value={contextValue}>
      {children}
    </AppContext.Provider>
  );
}

// Optymalizacja komponentów konsumujących
const MissionItem = memo(function MissionItem({ mission, onSelect }) {
  return (
    <li>
      {mission.name}
      <button onClick={() => onSelect(mission)}>Wybierz</button>
    </li>
  );
});

function MissionList() {
  const { missions, selectMission } = useMissions();

  // Memizacja callbacka
  const handleSelect = useCallback((mission) => {
    selectMission(mission);
  }, [selectMission]);

  return (
    <ul>
      {missions.map(mission => (
        <MissionItem
          key={mission.id}
          mission={mission}
          onSelect={handleSelect}
        />
      ))}
    </ul>
  );
}

Wprowadzenie do Redux Toolkit

Redux to popularna biblioteka do zarządzania stanem, która oferuje bardziej ustrukturyzowane podejście do globalnego stanu. Dzisiaj nowoczesny Redux to Redux Toolkit (RTK) - oficjalny, rekomendowany zestaw narzędzi, który eliminuje większość boilerplate'u. Zamiast ręcznie pisać reducery z instrukcją switch, używamy createSlice, a zamiast createStore - configureStore. Oto podstawy Redux Toolkit z React:

import { configureStore, createSlice } from '@reduxjs/toolkit';
import { Provider, useSelector, useDispatch } from 'react-redux';

// Slice = fragment stanu + reducery + akcje w jednym miejscu
const spaceAppSlice = createSlice({
  name: 'spaceApp',
  initialState: {
    missions: [],
    user: null
  },
  reducers: {
    // Dzięki Immerowi możemy "mutować" stan - RTK robi to bezpiecznie i niemutowalnie
    setUser: (state, action) => {
      state.user = action.payload;
    },
    setMissions: (state, action) => {
      state.missions = action.payload;
    }
  }
});

// createSlice automatycznie generuje kreatory akcji
export const { setUser, setMissions } = spaceAppSlice.actions;

// Store - configureStore sam dodaje DevTools i middleware
const store = configureStore({
  reducer: spaceAppSlice.reducer
});

// Provider
function App() {
  return (
    <Provider store={store}>
      <Main />
    </Provider>
  );
}

// Użycie w komponentach
function UserProfile() {
  // Wybieranie części stanu
  const user = useSelector(state => state.user);
  const dispatch = useDispatch();

  if (!user) return <p>Użytkownik nie zalogowany</p>;

  return (
    <div>
      <h2>{user.name}</h2>
      <button onClick={() => dispatch(setUser(null))}>
        Wyloguj
      </button>
    </div>
  );
}

Uwaga historyczna: Klasyczny Redux używał createStore i ręcznych reducerów z instrukcją switch. To podejście (import { createStore } from 'redux') jest dziś przestarzałe (deprecated) - oficjalna dokumentacja zaleca Redux Toolkit. Dlatego od razu uczymy się nowoczesnego sposobu.

Organizacja kodu w Redux Toolkit

W większych aplikacjach każdy fragment stanu to osobny slice. configureStore łączy je automatycznie - wystarczy podać mapę reducerów (nie potrzeba już ręcznego combineReducers):

// /store/index.js
import { configureStore } from '@reduxjs/toolkit';
import authReducer from './auth/authSlice';
import missionsReducer from './missions/missionsSlice';
import uiReducer from './ui/uiSlice';

// configureStore łączy reducery sam - bez combineReducers
const store = configureStore({
  reducer: {
    auth: authReducer,
    missions: missionsReducer,
    ui: uiReducer
  }
});
export default store;

// /store/missions/missionsSlice.js
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

// Operacje asynchroniczne obsługuje createAsyncThunk
export const fetchMissions = createAsyncThunk(
  'missions/fetchMissions',
  async () => {
    const missions = await api.fetchMissions();
    return missions;
  }
);

const missionsSlice = createSlice({
  name: 'missions',
  initialState: {
    list: [],
    active: null,
    loading: false,
    error: null
  },
  reducers: {
    setActiveMission: (state, action) => {
      state.active = action.payload;
    }
  },
  // extraReducers reagują na stany thunka (pending/fulfilled/rejected)
  extraReducers: (builder) => {
    builder
      .addCase(fetchMissions.pending, (state) => {
        state.loading = true;
      })
      .addCase(fetchMissions.fulfilled, (state, action) => {
        state.list = action.payload;
        state.loading = false;
      })
      .addCase(fetchMissions.rejected, (state, action) => {
        state.error = action.error.message;
        state.loading = false;
      });
  }
});

export const { setActiveMission } = missionsSlice.actions;
export default missionsSlice.reducer;

// /store/missions/selectors.js
export const selectMissions = state => state.missions.list;
export const selectActiveMission = state => state.missions.active;
export const selectMissionsLoading = state => state.missions.loading;

Nowoczesne alternatywy

W ekosystemie React pojawiło się wiele alternatywnych bibliotek do zarządzania stanem, które starają się uprościć proces i zmniejszyć ilość kodu boilerplate. Oto kilka popularnych opcji:

1. Zustand

Zustand to minimalistyczna biblioteka, która łączy prostotę hooka z potęgą store:

import create from 'zustand';

// Utworzenie store
const useSpaceStore = create((set) => ({
  missions: [],
  activeMissionId: null,
  isLoading: false,

  fetchMissions: async () => {
    set({ isLoading: true });
    try {
      const missions = await api.fetchMissions();
      set({ missions, isLoading: false });
    } catch (error) {
      set({ error: error.message, isLoading: false });
    }
  },

  setActiveMission: (id) => set({ activeMissionId: id })
}));

// Użycie w komponencie
function MissionPanel() {
  // Selektywne pobieranie danych ze store
  const missions = useSpaceStore(state => state.missions);
  const isLoading = useSpaceStore(state => state.isLoading);
  const fetchMissions = useSpaceStore(state => state.fetchMissions);

  useEffect(() => {
    fetchMissions();
  }, [fetchMissions]);

  if (isLoading) return <p>Ładowanie...</p>;

  return (
    <div>
      <h2>Misje</h2>
      <ul>
        {missions.map(mission => (
          <MissionItem key={mission.id} mission={mission} />
        ))}
      </ul>
    </div>
  );
}

2. Recoil

Recoil to biblioteka stworzona przez Facebook, która wprowadza koncepcję "atomów" i "selektorów":

import { atom, selector, useRecoilState, useRecoilValue } from 'recoil';

// Definiowanie atomów (najmniejszych jednostek stanu)
const missionsState = atom({
  key: 'missionsState',
  default: []
});

const missionsFilterState = atom({
  key: 'missionsFilterState',
  default: 'all' // 'all', 'active', 'completed'
});

// Selektor (pochodny stan)
const filteredMissionsState = selector({
  key: 'filteredMissionsState',
  get: ({ get }) => {
    const missions = get(missionsState);
    const filter = get(missionsFilterState);

    switch (filter) {
      case 'active':
        return missions.filter(mission => mission.status === 'active');
      case 'completed':
        return missions.filter(mission => mission.status === 'completed');
      default:
        return missions;
    }
  }
});

// Użycie w komponentach
function MissionsFilter() {
  const [filter, setFilter] = useRecoilState(missionsFilterState);

  return (
    <div>
      <button
        className={filter === 'all' ? 'active' : ''}
        onClick={() => setFilter('all')}
      >
        Wszystkie
      </button>
      <button
        className={filter === 'active' ? 'active' : ''}
        onClick={() => setFilter('active')}
      >
        Aktywne
      </button>
      <button
        className={filter === 'completed' ? 'active' : ''}
        onClick={() => setFilter('completed')}
      >
        Zakończone
      </button>
    </div>
  );
}

function MissionsList() {
  // Używanie filtrowanej wartości
  const missions = useRecoilValue(filteredMissionsState);

  return (
    <ul>
      {missions.map(mission => (
        <li key={mission.id}>{mission.name}</li>
      ))}
    </ul>
  );
}

3. Jotai

Jotai, podobnie jak Recoil, używa podejścia opartego na atomach, ale z bardziej minimalistycznym API:

import { atom, useAtom } from 'jotai';

// Definicja atomów
const userAtom = atom(null);
const missionsAtom = atom([]);
const missionFilterAtom = atom('all');

// Atom pochodny
const filteredMissionsAtom = atom(
  (get) => {
    const missions = get(missionsAtom);
    const filter = get(missionFilterAtom);

    switch (filter) {
      case 'active':
        return missions.filter(m => m.status === 'active');
      case 'completed':
        return missions.filter(m => m.status === 'completed');
      default:
        return missions;
    }
  }
);

// Komponent
function MissionDashboard() {
  const [missions, setMissions] = useAtom(missionsAtom);
  const [filter, setFilter] = useAtom(missionFilterAtom);
  const [filteredMissions] = useAtom(filteredMissionsAtom);

  // Logika komponentu...

  return (
    <div>
      {/* UI */}
    </div>
  );
}

Wybór odpowiedniego rozwiązania

Jak wybrać najlepsze rozwiązanie do zarządzania stanem dla swojej aplikacji? Oto kilka wskazówek:

  1. Rozmiar aplikacji:

    • Małe aplikacje: useState + useReducer + Context API
    • Średnie aplikacje: Zustand lub Jotai
    • Duże aplikacje: Redux (z Redux Toolkit) lub Recoil
  2. Złożoność stanu:

    • Prosty stan: useState
    • Średnio złożony stan: useReducer + Context API
    • Złożony stan z relacjami: Redux lub Recoil
  3. Wymagania dotyczące wydajności:

    • Jeśli wydajność renderowania jest kluczowa, rozważ biblioteki, które zapewniają granularną reaktywność (Recoil, Jotai)
  4. Doświadczenie zespołu:

    • Jeśli zespół zna Redux, może warto przy nim pozostać
    • Dla nowych projektów, prostsze API Zustand czy Jotai może przyspieszyć rozwój

Najlepsze praktyki

Niezależnie od wybranego rozwiązania, oto kilka ogólnych najlepszych praktyk dotyczących zarządzania globalnym stanem:

  1. Minimalizuj globalny stan - nie wszystko musi być globalne; używaj lokalnego stanu dla danych specyficznych dla komponentu

  2. Dziel stan według domen logicznych - grupuj powiązane dane i logikę razem

  3. Normalizuj dane - unikaj duplikacji i głębokich zagnieżdżeń

  4. Zachowuj niezmienność - nigdy nie modyfikuj stanu bezpośrednio

  5. Dokumentuj intencje - używaj opisowych nazw akcji i selektorów

  6. Używaj selektorów - do pobierania pochodnych danych

  7. Trzymaj logikę biznesową poza komponentami - w akcjach, reducerach lub dedykowanych hookach

// Przykład: Hook z logiką biznesową
function useMissionControl() {
  const { state, dispatch } = useAppState();

  const launchMission = useCallback(async (missionId) => {
    // Sprawdzenie warunków biznesowych
    if (!state.user || state.user.role !== 'commander') {
      throw new Error('Tylko dowódca może rozpocząć misję');
    }

    if (state.weather === 'storm') {
      throw new Error('Nie można wystartować podczas burzy');
    }

    // Logika biznesowa
    dispatch({ type: 'MISSION_LAUNCH_START', payload: missionId });

    try {
      await missionService.launch(missionId);
      dispatch({ type: 'MISSION_LAUNCH_SUCCESS', payload: missionId });
    } catch (error) {
      dispatch({ type: 'MISSION_LAUNCH_FAILURE', payload: error.message });
      throw error;
    }
  }, [state.user, state.weather, dispatch]);

  return {
    missions: state.missions,
    activeMission: state.activeMission,
    isLaunching: state.isLaunching,
    launchError: state.launchError,
    launchMission
  };
}

Podsumowanie

Globalne zarządzanie stanem jest kluczowym aspektem budowania skalowalnych aplikacji React. W tym module poznaliśmy różne podejścia:

  1. Context API + useReducer - wbudowane rozwiązanie React, dobre dla mniejszych i średnich aplikacji

  2. Podział na wiele kontekstów - sposób na organizację globalnego stanu według domen

  3. Optymalizacja wydajności - techniki minimalizacji przerenderowywania

  4. Redux - tradycyjna biblioteka z ustrukturyzowanym podejściem do zarządzania stanem

  5. Nowoczesne alternatywy - Zustand, Recoil, Jotai oferujące prostsze API i mniej kodu

Wybór odpowiedniego rozwiązania zależy od wielkości aplikacji, złożoności stanu i preferencji zespołu. Niezależnie od wyboru, postępowanie zgodnie z najlepszymi praktykami pomoże utrzymać czysty, przewidywalny i wydajny kod.

Kod do tej lekcji: App.jsx
import React, { useState, useEffect, useCallback, useRef } from 'react';

// Custom Hook: useLocalStorage
function useLocalStorage(key, initialValue) {
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      return initialValue;
    }
  });

  const setValue = (value) => {
    try {
      const valueToStore = value instanceof Function ? value(storedValue) : value;
      setStoredValue(valueToStore);
      window.localStorage.setItem(key, JSON.stringify(valueToStore));
    } catch (error) {
      console.log(error);
    }
  };

  return [storedValue, setValue];
}

// Custom Hook: useToggle
function useToggle(initialValue = false) {
  const [value, setValue] = useState(initialValue);
  const toggle = useCallback(() => setValue(v => !v), []);
  return [value, toggle];
}

// Custom Hook: useCounter
function useCounter(initialValue = 0, step = 1) {
  const [count, setCount] = useState(initialValue);

  const increment = useCallback(() => setCount(c => c + step), [step]);
  const decrement = useCallback(() => setCount(c => c - step), [step]);
  const reset = useCallback(() => setCount(initialValue), [initialValue]);

  return { count, increment, decrement, reset };
}

// Custom Hook: useFetch
function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      // Symulacja fetch
      setTimeout(() => {
        setData({
          ships: ['Explorer-1', 'Titan-7', 'Guardian-3'],
          missions: 12,
          crew: 45
        });
        setLoading(false);
      }, 1500);
    };
    fetchData();
  }, [url]);

  return { data, loading, error };
}

// Custom Hook: useWindowSize
function useWindowSize() {
  const [size, setSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight
  });

  useEffect(() => {
    const handleResize = () => {
      setSize({ width: window.innerWidth, height: window.innerHeight });
    };
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return size;
}

// Custom Hook: usePrevious
function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  }, [value]);
  return ref.current;
}

// Demo Component
function CustomHooksDemo() {
  // useLocalStorage demo
  const [name, setName] = useLocalStorage('astronaut-name', 'Kosmonauta');

  // useToggle demo
  const [isShieldActive, toggleShield] = useToggle(false);

  // useCounter demo
  const { count: fuel, increment: addFuel, decrement: useFuel, reset: resetFuel } = useCounter(50, 10);

  // useFetch demo
  const { data, loading, error } = useFetch('/api/station');

  // useWindowSize demo
  const { width, height } = useWindowSize();

  // usePrevious demo
  const previousFuel = usePrevious(fuel);

  return (
    <div style={{
      fontFamily: 'Arial, sans-serif',
      padding: '20px',
      maxWidth: '800px',
      margin: '0 auto',
      backgroundColor: '#0a0a1a',
      minHeight: '100vh',
      color: 'white'
    }}>
      <h1 style={{ textAlign: 'center', color: '#00d4ff' }}>Custom Hooks</h1>

      {/* useLocalStorage */}
      <section style={{ marginBottom: '30px', padding: '20px', backgroundColor: '#1a1a2e', borderRadius: '12px' }}>
        <h2 style={{ color: '#4caf50' }}>useLocalStorage</h2>
        <p>Nazwa astronauty (zapisywana w localStorage):</p>
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          style={{
            padding: '10px',
            width: '100%',
            boxSizing: 'border-box',
            borderRadius: '8px',
            border: '1px solid #333',
            backgroundColor: '#252545',
            color: 'white'
          }}
        />
        <p style={{ color: '#888', fontSize: '14px' }}>Odśwież stronę - wartość zostanie zachowana!</p>
      </section>

      {/* useToggle */}
      <section style={{ marginBottom: '30px', padding: '20px', backgroundColor: '#1a1a2e', borderRadius: '12px' }}>
        <h2 style={{ color: '#ff9800' }}>useToggle</h2>
        <div style={{ display: 'flex', alignItems: 'center', gap: '15px' }}>
          <button
            onClick={toggleShield}
            style={{
              padding: '12px 24px',
              backgroundColor: isShieldActive ? '#4caf50' : '#f44336',
              color: 'white',
              border: 'none',
              borderRadius: '8px',
              cursor: 'pointer'
            }}
          >
            {isShieldActive ? 'Tarcze AKTYWNE' : 'Tarcze WYŁĄCZONE'}
          </button>
        </div>
      </section>

      {/* useCounter */}
      <section style={{ marginBottom: '30px', padding: '20px', backgroundColor: '#1a1a2e', borderRadius: '12px' }}>
        <h2 style={{ color: '#2196f3' }}>useCounter</h2>
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: '48px', fontWeight: 'bold', color: fuel < 30 ? '#f44336' : '#4caf50' }}>
            {fuel}%
          </div>
          <p>Paliwo (poprzednio: {previousFuel ?? '-'}%)</p>
          <div style={{ display: 'flex', gap: '10px', justifyContent: 'center' }}>
            <button onClick={useFuel} style={{ padding: '10px 20px', backgroundColor: '#f44336', color: 'white', border: 'none', borderRadius: '8px', cursor: 'pointer' }}>-10</button>
            <button onClick={resetFuel} style={{ padding: '10px 20px', backgroundColor: '#666', color: 'white', border: 'none', borderRadius: '8px', cursor: 'pointer' }}>Reset</button>
            <button onClick={addFuel} style={{ padding: '10px 20px', backgroundColor: '#4caf50', color: 'white', border: 'none', borderRadius: '8px', cursor: 'pointer' }}>+10</button>
          </div>
        </div>
      </section>

      {/* useFetch */}
      <section style={{ marginBottom: '30px', padding: '20px', backgroundColor: '#1a1a2e', borderRadius: '12px' }}>
        <h2 style={{ color: '#9c27b0' }}>useFetch</h2>
        {loading ? (
          <p>Ładowanie danych stacji... ⏳</p>
        ) : (
          <div>
            <p>Statki: {data?.ships?.join(', ')}</p>
            <p>Aktywne misje: {data?.missions}</p>
            <p>Członkowie załogi: {data?.crew}</p>
          </div>
        )}
      </section>

      {/* useWindowSize */}
      <section style={{ padding: '20px', backgroundColor: '#1a1a2e', borderRadius: '12px' }}>
        <h2 style={{ color: '#e91e63' }}>useWindowSize</h2>
        <p>Rozmiar okna: {width} x {height} px</p>
        <p style={{ color: '#888', fontSize: '14px' }}>Zmień rozmiar okna przeglądarki!</p>
      </section>
    </div>
  );
}

export default CustomHooksDemo;

Hasła z dokumentacji w tej lekcji

Widzisz błąd w tej lekcji?

Sprawdź się

Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.

  1. 1. Kiedy używana jest domyślna wartość kontekstu przekazana do createContext?

  2. 2. Co się stanie, gdy komponent znajdzie się między dwoma Provider'ami tego samego kontekstu?

Zadania praktyczne w grze

  • Układanie w pionie

    Uporządkuj co się dzieje gdy zmienia się wartość w Provider:

  • Edytor kodu

    Implementuj system inwentarza kosmicznego

  • Układanie w pionie

    Uporządkuj etapy tworzenia systemu zarządzania flotą galaktyczną:

  • Edytor kodu

    Zaimplementuj centrum dowodzenia flotą

  1. PytanieWartości domyślne kontekstu
  2. Ułóż w kolejnościProces re-renderowania przy zmianie kontekstu
  3. Zadanie z kodemPraktyka: Context z useState
  4. PytanieWiele providerów
  5. Ułóż w kolejnościSystem galaktycznego dowodzenia
  6. Zadanie z kodemPraktyka: Context + Reducer

Przydatne artykuły