0%
React Hooks

Hooks

Advanced features

10-15 min

React Hooks

Hooks are functions that let you use state and other React features in function components. They were introduced in React 16.8 to simplify reusing logic between components.

Basic Hooks

useState

We already covered this in the previous chapter, but here is a quick reminder:

import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

useEffect

useEffect lets you handle side effects in function components:

import { useState, useEffect } from 'react';

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    // Effect that runs after every render
    fetchUser(userId).then(setUser);
  }, [userId]); // Dependency: the effect re-runs if userId changes

  if (!user) return <div>Chargement...</div>;
  return <div>{user.name}</div>;
}

Custom Hooks

Custom Hooks let you extract component logic into reusable functions:

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

  useEffect(() => {
    try {
      window.localStorage.setItem(key, JSON.stringify(storedValue));
    } catch (error) {
      console.error(error);
    }
  }, [key, storedValue]);

  return [storedValue, setStoredValue];
}

// Usage
function ThemeSwitcher() {
  const [theme, setTheme] = useLocalStorage('theme', 'light');
  return (
    <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
      {theme}
    </button>
  );
}

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!