Kurs JavaScript i React · Moduł 9: Nowoczesne hooki React

useId - unikalne identyfikatory dla dostępności

16 min czytania ·
W tej lekcji5

Na pokładzie każdy przełącznik ma tabliczkę z opisem. Jeśli dwa przełączniki dostaną tę samą tabliczkę, astronauta pociągnie nie ten, co trzeba. W HTML rolę takiej tabliczki pełni powiązanie <label htmlFor> z id pola, a czytniki ekranu polegają na nim całkowicie. Kłopot zaczyna się, gdy ten sam komponent formularza pojawia się na ekranie trzy razy: skąd wziąć trzy różne, przewidywalne identyfikatory?

Hook useId jest prostym, ale niezwykle ważnym narzędziem wprowadzonym w React 18. Generuje unikalne identyfikatory, które są stabilne zarówno po stronie serwera, jak i klienta, co jest kluczowe dla dostępności (accessibility) i poprawnego renderowania SSR.

Podstawy useId

1. Problem, który rozwiązuje useId

Zacznijmy od dwóch popularnych, ale błędnych pomysłów, a potem porównajmy je z useId:

// PROBLEM - niestabilne ID
function BadExample() {
  // Math.random() da różne wartości na serwerze i kliencie!
  const id = Math.random().toString(36).substr(2, 9);

  return (
    <div>
      <label htmlFor={id}>Email:</label>
      <input id={id} type="email" />
    </div>
  );
}

// PROBLEM - globalne liczniki
let counter = 0;
function AnotherBadExample() {
  // Counter może być różny w różnych renderach
  const id = `input-${counter++}`;

  return (
    <div>
      <label htmlFor={id}>Hasło:</label>
      <input id={id} type="password" />
    </div>
  );
}

// ROZWIĄZANIE - useId
import { useId } from 'react';

function GoodExample() {
  const id = useId();

  return (
    <div>
      <label htmlFor={id}>Imię:</label>
      <input id={id} type="text" />
    </div>
  );
}

Math.random() daje inną wartość na serwerze i w przeglądarce, więc hydratacja zgłosi niezgodność. Globalny licznik zależy od kolejności renderowania, która przy SSR i Suspense bywa różna. useId opiera się na pozycji komponentu w drzewie, dlatego serwer i klient wyliczą ten sam identyfikator.

2. Podstawowe użycie dla pojedynczych elementów

Najczęstszy scenariusz to komponent pola, który sam łączy etykietę z inputem. Każda instancja wywołuje hook osobno:

import { useId } from 'react';

function AccessibleInput({ label, type = 'text', ...props }) {
  const id = useId();

  return (
    <div style={{ marginBottom: '15px' }}>
      <label
        htmlFor={id}
        style={{
          display: 'block',
          marginBottom: '5px',
          fontWeight: 'bold'
        }}
      >
        {label}
      </label>
      <input
        id={id}
        type={type}
        style={{
          width: '100%',
          padding: '8px',
          border: '1px solid #ddd',
          borderRadius: '4px'
        }}
        {...props}
      />
    </div>
  );
}

// Użycie komponentu
function RegistrationForm() {
  return (
    <form style={{ maxWidth: '400px', margin: '0 auto' }}>
      <h2>Rejestracja</h2>
      <AccessibleInput label="Imię:" />
      <AccessibleInput label="Nazwisko:" />
      <AccessibleInput label="Email:" type="email" />
      <AccessibleInput label="Hasło:" type="password" />
      <button type="submit">Zarejestruj się</button>
    </form>
  );
}

Cztery pola AccessibleInput dostają cztery różne identyfikatory, choć korzystają z tego samego kodu. Kliknięcie etykiety ustawia fokus w polu, a czytnik ekranu odczyta jego nazwę.

3. Użycie z wieloma powiązanymi elementami

Gdy potrzebujesz wielu identyfikatorów, nie wywołuj hooka w pętli. Wywołaj go raz i doklejaj przyrostki:

import { useId } from 'react';

function RadioGroup({ label, options, name, onChange }) {
  const baseId = useId();

  return (
    <fieldset style={{ border: '1px solid #ddd', borderRadius: '8px', padding: '15px' }}>
      <legend style={{ fontWeight: 'bold', padding: '0 10px' }}>{label}</legend>
      {options.map((option, index) => {
        const optionId = `${baseId}-${index}`;

        return (
          <div key={option.value} style={{ marginBottom: '10px' }}>
            <input
              type="radio"
              id={optionId}
              name={name}
              value={option.value}
              onChange={onChange}
              style={{ marginRight: '8px' }}
            />
            <label htmlFor={optionId} style={{ cursor: 'pointer' }}>
              {option.label}
            </label>
          </div>
        );
      })}
    </fieldset>
  );
}

// Użycie
function PreferencesForm() {
  const handleThemeChange = (e) => console.log('Theme:', e.target.value);
  const handleLanguageChange = (e) => console.log('Language:', e.target.value);

  return (
    <div style={{ maxWidth: '500px', margin: '0 auto' }}>
      <h2>Preferencje</h2>

      <RadioGroup
        label="Wybierz motyw:"
        name="theme"
        onChange={handleThemeChange}
        options={[
          { value: 'light', label: 'Jasny' },
          { value: 'dark', label: 'Ciemny' },
          { value: 'auto', label: 'Automatyczny' }
        ]}
      />

      <div style={{ marginTop: '20px' }}>
        <RadioGroup
          label="Język interfejsu:"
          name="language"
          onChange={handleLanguageChange}
          options={[
            { value: 'pl', label: 'Polski' },
            { value: 'en', label: 'English' },
            { value: 'de', label: 'Deutsch' }
          ]}
        />
      </div>
    </div>
  );
}

Każda grupa radiowa ma własne baseId, więc opcje z grupy "motyw" nie zderzą się z opcjami grupy "język". Zauważ, że klucze listy dalej pochodzą z danych, option.value, a nie z useId.

Zaawansowane wzorce z useId

1. Komponenty z opisami ARIA

Atrybut aria-describedby wskazuje identyfikatory elementów z tekstem pomocniczym lub błędem, a aria-invalid informuje, że wartość jest niepoprawna. Najpierw komponent pola:

import { useId } from 'react';

function AccessibleTextField({
  label,
  helperText,
  errorText,
  required = false,
  ...props
}) {
  const inputId = useId();
  const helperId = useId();
  const errorId = useId();

  const ariaDescribedBy = [
    helperText && helperId,
    errorText && errorId
  ].filter(Boolean).join(' ');

  return (
    <div style={{ marginBottom: '20px' }}>
      <label
        htmlFor={inputId}
        style={{
          display: 'block',
          marginBottom: '5px',
          fontWeight: 'bold'
        }}
      >
        {label}
        {required && <span style={{ color: 'red' }}> *</span>}
      </label>

      <input
        id={inputId}
        aria-describedby={ariaDescribedBy || undefined}
        aria-invalid={!!errorText}
        aria-required={required}
        style={{
          width: '100%',
          padding: '10px',
          border: `2px solid ${errorText ? '#dc3545' : '#ddd'}`,
          borderRadius: '4px',
          fontSize: '16px'
        }}
        {...props}
      />

      {helperText && !errorText && (
        <div
          id={helperId}
          style={{
            marginTop: '5px',
            fontSize: '14px',
            color: '#666'
          }}
        >
          {helperText}
        </div>
      )}

      {errorText && (
        <div
          id={errorId}
          role="alert"
          style={{
            marginTop: '5px',
            fontSize: '14px',
            color: '#dc3545'
          }}
        >
          {errorText}
        </div>
      )}
    </div>
  );
}

Opis i błąd są dołączane do pola tylko wtedy, gdy istnieją, a role="alert" sprawia, że czytnik od razu ogłosi błąd. Teraz formularz, który z niego korzysta:

// Przykład użycia z walidacją
function ContactForm() {
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [errors, setErrors] = useState({});

  const validateEmail = (value) => {
    if (!value) return 'Email jest wymagany';
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
      return 'Nieprawidłowy format email';
    }
    return '';
  };

  const validatePhone = (value) => {
    if (value && !/^\d{9}$/.test(value.replace(/\s/g, ''))) {
      return 'Numer telefonu powinien mieć 9 cyfr';
    }
    return '';
  };

  const handleEmailChange = (e) => {
    const value = e.target.value;
    setEmail(value);
    setErrors(prev => ({ ...prev, email: validateEmail(value) }));
  };

  const handlePhoneChange = (e) => {
    const value = e.target.value;
    setPhone(value);
    setErrors(prev => ({ ...prev, phone: validatePhone(value) }));
  };

  return (
    <form style={{ maxWidth: '500px', margin: '0 auto' }}>
      <h2>Formularz kontaktowy</h2>

      <AccessibleTextField
        label="Adres email"
        type="email"
        value={email}
        onChange={handleEmailChange}
        helperText="Użyjemy tego adresu tylko do kontaktu w sprawie Twojego zapytania"
        errorText={errors.email}
        required
      />

      <AccessibleTextField
        label="Numer telefonu"
        type="tel"
        value={phone}
        onChange={handlePhoneChange}
        helperText="Opcjonalnie - przyspieszy kontakt"
        errorText={errors.phone}
      />

      <button
        type="submit"
        disabled={!!errors.email || !!errors.phone}
        style={{
          padding: '10px 20px',
          backgroundColor: '#007bff',
          color: 'white',
          border: 'none',
          borderRadius: '4px',
          cursor: 'pointer',
          fontSize: '16px'
        }}
      >
        Wyślij
      </button>
    </form>
  );
}

Formularz nie zna żadnych identyfikatorów, bo to AccessibleTextField zarządza nimi w środku.

2. Komponenty typu accordion/collapse

Wzorzec akordeonu z wytycznych WAI-ARIA wymaga powiązania przycisku z panelem przez aria-controls i aria-labelledby. Dwa wywołania useId w AccordionItem wystarczą:

import { useId, useState } from 'react';

function Accordion({ items }) {
  const [openIndex, setOpenIndex] = useState(null);

  return (
    <div style={{ border: '1px solid #ddd', borderRadius: '8px', overflow: 'hidden' }}>
      {items.map((item, index) => (
        <AccordionItem
          key={index}
          title={item.title}
          content={item.content}
          isOpen={openIndex === index}
          onToggle={() => setOpenIndex(openIndex === index ? null : index)}
        />
      ))}
    </div>
  );
}

function AccordionItem({ title, content, isOpen, onToggle }) {
  const headerId = useId();
  const panelId = useId();

  return (
    <div style={{ borderBottom: '1px solid #ddd' }}>
      <h3 style={{ margin: 0 }}>
        <button
          id={headerId}
          aria-expanded={isOpen}
          aria-controls={panelId}
          onClick={onToggle}
          style={{
            width: '100%',
            padding: '15px 20px',
            border: 'none',
            background: isOpen ? '#f8f9fa' : 'white',
            textAlign: 'left',
            fontSize: '16px',
            cursor: 'pointer',
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center'
          }}
        >
          <span>{title}</span>
          <span style={{
            transform: isOpen ? 'rotate(180deg)' : 'rotate(0)',
            transition: 'transform 0.3s'
          }}>
            ▼
          </span>
        </button>
      </h3>

      <div
        id={panelId}
        role="region"
        aria-labelledby={headerId}
        hidden={!isOpen}
        style={{
          padding: isOpen ? '20px' : '0 20px',
          maxHeight: isOpen ? '500px' : '0',
          overflow: 'hidden',
          transition: 'all 0.3s ease-in-out',
          backgroundColor: '#f8f9fa'
        }}
      >
        {content}
      </div>
    </div>
  );
}

// Użycie
function FAQSection() {
  const faqItems = [
    {
      title: 'Czym jest useId?',
      content: 'useId to hook React, który generuje unikalne identyfikatory stabilne między serwerem a klientem. Jest szczególnie przydatny dla dostępności.'
    },
    {
      title: 'Kiedy używać useId?',
      content: 'Używaj useId zawsze, gdy potrzebujesz unikalnych ID dla elementów HTML, szczególnie dla powiązań label-input, ARIA attributes, czy innych relacji między elementami.'
    },
    {
      title: 'Czy useId jest bezpieczny dla SSR?',
      content: 'Tak! useId został specjalnie zaprojektowany, aby generować te same ID na serwerze i kliencie, eliminując problemy z hydratacją.'
    }
  ];

  return (
    <div style={{ maxWidth: '600px', margin: '0 auto', padding: '20px' }}>
      <h2>Często zadawane pytania</h2>
      <Accordion items={faqItems} />
    </div>
  );
}

Atrybut aria-expanded mówi, czy panel jest otwarty, a hidden ukrywa zamkniętą treść także przed czytnikiem.

3. Zaawansowane formularze z walidacją

Pole hasła ma trzy powiązane elementy: input, wskaźnik siły i listę wymagań. Najpierw logika oceny hasła:

import { useId, useState } from 'react';

function PasswordField({
  label = "Hasło",
  value,
  onChange,
  showStrength = true
}) {
  const [showPassword, setShowPassword] = useState(false);
  const inputId = useId();
  const strengthId = useId();
  const requirementsId = useId();

  const calculateStrength = (password) => {
    let strength = 0;
    if (password.length >= 8) strength++;
    if (/[a-z]/.test(password) && /[A-Z]/.test(password)) strength++;
    if (/\d/.test(password)) strength++;
    if (/[^a-zA-Z0-9]/.test(password)) strength++;
    return strength;
  };

  const strength = calculateStrength(value);
  const strengthLabels = ['Bardzo słabe', 'Słabe', 'Średnie', 'Silne', 'Bardzo silne'];
  const strengthColors = ['#dc3545', '#fd7e14', '#ffc107', '#28a745', '#20c997'];

  const requirements = [
    { met: value.length >= 8, text: 'Minimum 8 znaków' },
    { met: /[a-z]/.test(value) && /[A-Z]/.test(value), text: 'Małe i wielkie litery' },
    { met: /\d/.test(value), text: 'Przynajmniej jedna cyfra' },
    { met: /[^a-zA-Z0-9]/.test(value), text: 'Przynajmniej jeden znak specjalny' }
  ];

Siła to liczba spełnionych warunków, od 0 do 4, co pasuje do pięciu etykiet w strengthLabels. Teraz widok pola:

  return (
    <div style={{ marginBottom: '20px' }}>
      <label
        htmlFor={inputId}
        style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}
      >
        {label}
      </label>

      <div style={{ position: 'relative' }}>
        <input
          id={inputId}
          type={showPassword ? 'text' : 'password'}
          value={value}
          onChange={onChange}
          aria-describedby={`${strengthId} ${requirementsId}`}
          style={{
            width: '100%',
            padding: '10px 40px 10px 10px',
            border: '2px solid #ddd',
            borderRadius: '4px',
            fontSize: '16px'
          }}
        />

        <button
          type="button"
          onClick={() => setShowPassword(!showPassword)}
          aria-label={showPassword ? 'Ukryj hasło' : 'Pokaż hasło'}
          style={{
            position: 'absolute',
            right: '10px',
            top: '50%',
            transform: 'translateY(-50%)',
            background: 'none',
            border: 'none',
            cursor: 'pointer',
            fontSize: '20px'
          }}
        >
          {showPassword ? 'Ukryj' : 'Pokaż'}
        </button>
      </div>

      {showStrength && value && (
        <>
          <div
            id={strengthId}
            style={{ marginTop: '10px' }}
            role="status"
            aria-live="polite"
          >
            <div style={{
              display: 'flex',
              justifyContent: 'space-between',
              marginBottom: '5px',
              fontSize: '14px'
            }}>
              <span>Siła hasła:</span>
              <span style={{ color: strengthColors[strength], fontWeight: 'bold' }}>
                {strengthLabels[strength]}
              </span>
            </div>

            <div style={{
              height: '4px',
              backgroundColor: '#e9ecef',
              borderRadius: '2px',
              overflow: 'hidden'
            }}>
              <div style={{
                width: `${(strength + 1) * 20}%`,
                height: '100%',
                backgroundColor: strengthColors[strength],
                transition: 'all 0.3s ease'
              }} />
            </div>
          </div>

          <ul
            id={requirementsId}
            style={{
              marginTop: '10px',
              paddingLeft: '20px',
              fontSize: '14px'
            }}
          >
            {requirements.map((req, index) => (
              <li
                key={index}
                style={{
                  color: req.met ? '#28a745' : '#6c757d',
                  listStyleType: 'none'
                }}
              >
                {req.met ? '√ ' : '○ '}{req.text}
              </li>
            ))}
          </ul>
        </>
      )}
    </div>
  );
}

Input wskazuje przez aria-describedby oba identyfikatory naraz, a aria-live="polite" ogłasza zmianę siły bez przerywania użytkownika. Całość składamy w formularz rejestracji:

// Kompletny formularz rejestracji
function SecureRegistrationForm() {
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: '',
    confirmPassword: ''
  });

  const [agreed, setAgreed] = useState(false);
  const checkboxId = useId();

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('Form submitted:', formData);
  };

  const passwordsMatch = formData.password === formData.confirmPassword;

  return (
    <form
      onSubmit={handleSubmit}
      style={{ maxWidth: '500px', margin: '0 auto', padding: '20px' }}
    >
      <h2>Bezpieczna rejestracja</h2>

      <AccessibleTextField
        label="Nazwa użytkownika"
        value={formData.username}
        onChange={(e) => setFormData(prev => ({ ...prev, username: e.target.value }))}
        helperText="3-20 znaków, tylko litery i cyfry"
        required
      />

      <AccessibleTextField
        label="Email"
        type="email"
        value={formData.email}
        onChange={(e) => setFormData(prev => ({ ...prev, email: e.target.value }))}
        required
      />

      <PasswordField
        label="Hasło"
        value={formData.password}
        onChange={(e) => setFormData(prev => ({ ...prev, password: e.target.value }))}
      />

      <PasswordField
        label="Potwierdź hasło"
        value={formData.confirmPassword}
        onChange={(e) => setFormData(prev => ({ ...prev, confirmPassword: e.target.value }))}
        showStrength={false}
      />

      {formData.confirmPassword && !passwordsMatch && (
        <div style={{ color: '#dc3545', fontSize: '14px', marginTop: '-15px', marginBottom: '15px' }}>
          Hasła nie są identyczne
        </div>
      )}

      <div style={{ marginBottom: '20px' }}>
        <input
          type="checkbox"
          id={checkboxId}
          checked={agreed}
          onChange={(e) => setAgreed(e.target.checked)}
          style={{ marginRight: '8px' }}
        />
        <label htmlFor={checkboxId} style={{ fontSize: '14px' }}>
          Akceptuję <a href="#">regulamin</a> i <a href="#">politykę prywatności</a>
        </label>
      </div>

      <button
        type="submit"
        disabled={!agreed || !passwordsMatch || !formData.password}
        style={{
          width: '100%',
          padding: '12px',
          backgroundColor: '#007bff',
          color: 'white',
          border: 'none',
          borderRadius: '4px',
          fontSize: '16px',
          cursor: 'pointer',
          opacity: (!agreed || !passwordsMatch || !formData.password) ? 0.6 : 1
        }}
      >
        Zarejestruj się
      </button>
    </form>
  );
}

Checkbox zgody dostał własne useId bezpośrednio w formularzu, bo nie jest osobnym komponentem.

Praktyczne zastosowania useId

1. Komponenty wielokrotnego użytku

Przełącznik i ocena gwiazdkami to klasyczne komponenty z biblioteki UI, które mogą wystąpić wiele razy na stronie:

import { useId, Fragment } from 'react';

// Uniwersalny komponent Toggle/Switch
function Toggle({ label, checked, onChange, disabled = false }) {
  const id = useId();

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
      <input
        type="checkbox"
        id={id}
        checked={checked}
        onChange={onChange}
        disabled={disabled}
        style={{ display: 'none' }}
      />
      <label
        htmlFor={id}
        style={{
          position: 'relative',
          width: '50px',
          height: '24px',
          backgroundColor: checked ? '#007bff' : '#ccc',
          borderRadius: '12px',
          cursor: disabled ? 'not-allowed' : 'pointer',
          opacity: disabled ? 0.6 : 1,
          transition: 'background-color 0.3s'
        }}
      >
        <span
          style={{
            position: 'absolute',
            top: '2px',
            left: checked ? '26px' : '2px',
            width: '20px',
            height: '20px',
            backgroundColor: 'white',
            borderRadius: '50%',
            transition: 'left 0.3s',
            boxShadow: '0 2px 4px rgba(0,0,0,0.2)'
          }}
        />
      </label>
      <span style={{ fontSize: '14px' }}>{label}</span>
    </div>
  );
}

// Komponent do oceny (rating)
function StarRating({ label, value, onChange, max = 5 }) {
  const baseId = useId();

  return (
    <div>
      <div style={{ marginBottom: '5px', fontWeight: 'bold' }}>
        {label}
      </div>
      <div style={{ display: 'flex', gap: '5px' }}>
        {Array.from({ length: max }, (_, i) => {
          const ratingValue = i + 1;
          const inputId = `${baseId}-${ratingValue}`;

          return (
            <Fragment key={ratingValue}>
              <input
                type="radio"
                id={inputId}
                name={`rating-${baseId}`}
                value={ratingValue}
                checked={value === ratingValue}
                onChange={() => onChange(ratingValue)}
                style={{ display: 'none' }}
              />
              <label
                htmlFor={inputId}
                style={{
                  fontSize: '24px',
                  cursor: 'pointer',
                  color: ratingValue <= value ? '#ffc107' : '#ddd'
                }}
              >
                ◆
              </label>
            </Fragment>
          );
        })}
      </div>
    </div>
  );
}

Uwaga na jeden szczegół: display: 'none' usuwa input z drzewa dostępności i z nawigacji klawiaturą. W produkcji lepiej ukryć go wizualnie klasą typu "visually hidden", żeby przełącznik dało się obsłużyć klawiszem Tab.

2. Komponenty z podpowiedziami (tooltip)

Podpowiedź powinna być powiązana z przyciskiem przez aria-describedby i pojawiać się także przy fokusie, nie tylko po najechaniu myszą:

import { useId, useState } from 'react';

function TooltipButton({ buttonText, tooltipText }) {
  const [showTooltip, setShowTooltip] = useState(false);
  const tooltipId = useId();

  return (
    <div style={{ position: 'relative', display: 'inline-block' }}>
      <button
        aria-describedby={showTooltip ? tooltipId : undefined}
        onMouseEnter={() => setShowTooltip(true)}
        onMouseLeave={() => setShowTooltip(false)}
        onFocus={() => setShowTooltip(true)}
        onBlur={() => setShowTooltip(false)}
        style={{
          padding: '10px 20px',
          backgroundColor: '#007bff',
          color: 'white',
          border: 'none',
          borderRadius: '4px',
          cursor: 'pointer'
        }}
      >
        {buttonText}
      </button>

      {showTooltip && (
        <div
          id={tooltipId}
          role="tooltip"
          style={{
            position: 'absolute',
            bottom: '100%',
            left: '50%',
            transform: 'translateX(-50%)',
            marginBottom: '10px',
            padding: '8px 12px',
            backgroundColor: 'rgba(0,0,0,0.8)',
            color: 'white',
            borderRadius: '4px',
            fontSize: '14px',
            whiteSpace: 'nowrap',
            zIndex: 1000
          }}
        >
          {tooltipText}
          <div style={{
            position: 'absolute',
            top: '100%',
            left: '50%',
            transform: 'translateX(-50%)',
            width: 0,
            height: 0,
            borderLeft: '5px solid transparent',
            borderRight: '5px solid transparent',
            borderTop: '5px solid rgba(0,0,0,0.8)'
          }} />
        </div>
      )}
    </div>
  );
}

Rola tooltip i obsługa onFocus oraz onBlur sprawiają, że użytkownik klawiatury dostaje tę samą informację co użytkownik myszy.

Najlepsze praktyki z useId

1. Kiedy używać useId

Poniższe przykłady zbierają dobre i złe zastosowania:

// DOBRZE - elementy formularza
function GoodForm() {
  const emailId = useId();
  return (
    <>
      <label htmlFor={emailId}>Email:</label>
      <input id={emailId} type="email" />
    </>
  );
}

// DOBRZE - ARIA relationships
function GoodAria() {
  const descriptionId = useId();
  return (
    <>
      <input aria-describedby={descriptionId} />
      <span id={descriptionId}>Pomocny opis</span>
    </>
  );
}

// ŹLE - jako klucze w listach
function BadList({ items }) {
  return items.map(item => {
    const id = useId(); // Nie używaj w pętlach!
    return <li key={id}>{item}</li>;
  });
}

// ŹLE - do identyfikacji danych
function BadData() {
  const user = {
    id: useId(), // Nie do danych!
    name: 'Jan'
  };
}

Dokumentacja react.dev mówi wprost: useId nie służy do generowania kluczy listy ani identyfikatorów danych. Klucze powinny pochodzić z danych, a hook i tak nie może być wywołany w pętli.

2. Prefiksy dla lepszej organizacji

Możesz opakować hook we własną funkcję dodającą prefiks:

import { useId } from 'react';

function createIdGenerator(prefix) {
  return function useIdWithPrefix() {
    const id = useId();
    return `${prefix}-${id}`;
  };
}

// Użycie
const useFormId = createIdGenerator('form');
const useModalId = createIdGenerator('modal');
const useTabId = createIdGenerator('tab');

function MyForm() {
  const emailId = useFormId();
  const passwordId = useFormId();

  // Wygenerowane ID będą wyglądać jak: form-_r_1_, form-_r_2_ (starsze wersje React: form-:r1:)
}

Format samego identyfikatora zależy od wersji React, dlatego nie buduj na nim żadnej logiki. Gdy na jednej stronie działa kilka aplikacji React, użyj oficjalnej opcji identifierPrefix w createRoot lub hydrateRoot.

3. Testowanie komponentów z useId

Testy nie powinny zależeć od wygenerowanych wartości. Szukaj pól po etykiecie, tak jak użytkownik:

// Komponenty używające useId są łatwe do testowania
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

function LoginForm() {
  const usernameId = useId();
  const passwordId = useId();

  return (
    <form>
      <label htmlFor={usernameId}>Username:</label>
      <input id={usernameId} type="text" />

      <label htmlFor={passwordId}>Password:</label>
      <input id={passwordId} type="password" />

      <button type="submit">Login</button>
    </form>
  );
}

// Test
test('form inputs are properly labeled', async () => {
  render(<LoginForm />);

  // Możemy znaleźć inputy przez ich labels
  const usernameInput = screen.getByLabelText('Username:');
  const passwordInput = screen.getByLabelText('Password:');

  await userEvent.type(usernameInput, 'testuser');
  await userEvent.type(passwordInput, 'password123');

  expect(usernameInput).toHaveValue('testuser');
  expect(passwordInput).toHaveValue('password123');
});

getByLabelText działa tylko wtedy, gdy etykieta jest poprawnie powiązana z polem, więc test sprawdza przy okazji dostępność.

Powtórka: memoizacja przed zadaniami

Zadania po tej lekcji wracają do memoizacji. useMemo zapamiętuje wynik obliczeń, a useCallback samą funkcję, czyli jej stabilną referencję między renderami. memo pomija render komponentu, gdy propsy się nie zmieniły:

import { useMemo, useCallback, memo } from 'react';

const PlanetList = memo(function PlanetList({ planets, onSelect }) {
  return planets.map(p => (
    <button key={p.id} onClick={() => onSelect(p.id)}>{p.name}</button>
  ));
});

function Observatory({ planets, query }) {
  // useMemo: zapamiętany WYNIK filtrowania
  const visible = useMemo(
    () => planets.filter(p => p.name.includes(query)),
    [planets, query]
  );
  // useCallback: zapamiętana FUNKCJA (ta sama referencja)
  const handleSelect = useCallback((id) => console.log('Wybrano', id), []);

  return <PlanetList planets={visible} onSelect={handleSelect} />;
}

Bez useCallback każda nowa funkcja handleSelect unieważniałaby memo. Nie owijaj jednak wszystkiego: porównywanie propsów też kosztuje i przy prostych komponentach bywa droższe niż sam render.

useId to prosty, ale potężny hook, który znacząco poprawia dostępność aplikacji React. Używaj go wszędzie tam, gdzie potrzebujesz stabilnych, unikalnych identyfikatorów dla elementów HTML.

Moja rada: każde pole formularza w bibliotece komponentów niech od razu dostaje useId. Pamiętaj: useId to tabliczka przy przełączniku, dzięki której każdy członek załogi trafi we właściwy.

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

// Demonstracja useId - generowanie stabilnych, unikalnych identyfikatorów
// Kluczowe dla dostępności (accessibility) i SSR

// Komponent formularza z useId - każda instancja ma unikalne ID
function CrewMemberForm({ title }) {
  // useId generuje unikalny prefix dla tej instancji komponentu
  const id = useId();

  const [name, setName] = useState('');
  const [role, setRole] = useState('');
  const [clearance, setClearance] = useState('standard');

  const nameId = id + '-name';
  const roleId = id + '-role';
  const clearanceId = id + '-clearance';
  const nameErrorId = id + '-name-error';

  const nameError = name.length > 0 && name.length < 2 ? 'Imię musi mieć min. 2 znaki' : '';

  return (
    <fieldset style={{ background: '#1b2838', padding: '16px', borderRadius: '12px', border: '1px solid #415a77', margin: 0 }}>
      <legend style={{ color: '#00d4ff', fontWeight: 'bold', padding: '0 8px' }}>{title}</legend>

      <div style={{ marginBottom: '12px' }}>
        <label htmlFor={nameId} style={{ display: 'block', color: '#778da9', marginBottom: '4px', fontSize: '13px' }}>
          Imię członka załogi:
        </label>
        <input
          id={nameId}
          value={name}
          onChange={e => setName(e.target.value)}
          aria-describedby={nameError ? nameErrorId : undefined}
          aria-invalid={!!nameError}
          placeholder="np. Kapitan Nova"
          style={{
            width: '100%',
            padding: '8px 12px',
            borderRadius: '8px',
            border: '1px solid ' + (nameError ? '#ff6b6b' : '#415a77'),
            background: '#0d1b2a',
            color: '#e0e1dd',
            boxSizing: 'border-box',
          }}
        />
        {nameError && (
          <p id={nameErrorId} role="alert" style={{ color: '#ff6b6b', fontSize: '12px', margin: '4px 0 0' }}>
            {nameError}
          </p>
        )}
      </div>

      <div style={{ marginBottom: '12px' }}>
        <label htmlFor={roleId} style={{ display: 'block', color: '#778da9', marginBottom: '4px', fontSize: '13px' }}>
          Stanowisko:
        </label>
        <input
          id={roleId}
          value={role}
          onChange={e => setRole(e.target.value)}
          placeholder="np. Nawigator"
          style={{ width: '100%', padding: '8px 12px', borderRadius: '8px', border: '1px solid #415a77', background: '#0d1b2a', color: '#e0e1dd', boxSizing: 'border-box' }}
        />
      </div>

      <div>
        <label htmlFor={clearanceId} style={{ display: 'block', color: '#778da9', marginBottom: '4px', fontSize: '13px' }}>
          Poziom dostępu:
        </label>
        <select
          id={clearanceId}
          value={clearance}
          onChange={e => setClearance(e.target.value)}
          style={{ width: '100%', padding: '8px 12px', borderRadius: '8px', border: '1px solid #415a77', background: '#0d1b2a', color: '#e0e1dd', boxSizing: 'border-box' }}
        >
          <option value="standard">Standardowy</option>
          <option value="elevated">Podwyższony</option>
          <option value="command">Dowódczy</option>
        </select>
      </div>

      <div style={{ marginTop: '12px', background: '#0d1b2a', padding: '8px 12px', borderRadius: '8px' }}>
        <p style={{ color: '#778da9', margin: 0, fontSize: '11px' }}>
          useId prefix: <code style={{ color: '#00d4ff' }}>{id}</code>
        </p>
        <p style={{ color: '#778da9', margin: '2px 0 0', fontSize: '11px' }}>
          IDs: <code style={{ color: '#00ff88' }}>{nameId}</code>, <code style={{ color: '#00ff88' }}>{roleId}</code>, <code style={{ color: '#00ff88' }}>{clearanceId}</code>
        </p>
      </div>
    </fieldset>
  );
}

// Komponent z wieloma grupami radio - każda potrzebuje unikalnej nazwy
function MissionPrioritySelector() {
  const id = useId();
  const [priority, setPriority] = useState('medium');

  const priorities = [
    { value: 'low', label: 'Niski', color: '#00ff88' },
    { value: 'medium', label: 'Średni', color: '#ffaa00' },
    { value: 'high', label: 'Wysoki', color: '#ff6b6b' },
    { value: 'critical', label: 'Krytyczny', color: '#ff0044' },
  ];

  return (
    <div style={{ background: '#1b2838', padding: '16px', borderRadius: '12px', border: '1px solid #415a77' }}>
      <h3 style={{ color: '#00d4ff', margin: '0 0 12px', fontSize: '14px' }}>Priorytet misji</h3>
      <div role="radiogroup" aria-labelledby={id + '-label'} style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
        <span id={id + '-label'} className="sr-only" style={{ position: 'absolute', width: '1px', height: '1px', overflow: 'hidden' }}>
          Wybierz priorytet misji
        </span>
        {priorities.map(p => (
          <label
            key={p.value}
            htmlFor={id + '-' + p.value}
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: '6px',
              padding: '8px 14px',
              borderRadius: '8px',
              border: '1px solid ' + (priority === p.value ? p.color : '#415a77'),
              background: priority === p.value ? p.color + '22' : 'transparent',
              cursor: 'pointer',
            }}
          >
            <input
              type="radio"
              id={id + '-' + p.value}
              name={id + '-priority'}
              value={p.value}
              checked={priority === p.value}
              onChange={() => setPriority(p.value)}
              style={{ accentColor: p.color }}
            />
            <span style={{ color: priority === p.value ? p.color : '#778da9', fontSize: '13px' }}>{p.label}</span>
          </label>
        ))}
      </div>
      <p style={{ color: '#778da9', fontSize: '11px', margin: '8px 0 0' }}>
        Radio group name: <code style={{ color: '#00d4ff' }}>{id}-priority</code> (unikalna dzięki useId)
      </p>
    </div>
  );
}

// Główna aplikacja - wiele instancji tego samego komponentu
export default function App() {
  const [formCount, setFormCount] = useState(2);

  return (
    <div style={{ background: '#0d1b2a', minHeight: '100vh', padding: '20px', color: '#e0e1dd', fontFamily: 'monospace' }}>
      <div style={{ maxWidth: '550px', margin: '0 auto' }}>
        <h1 style={{ color: '#00d4ff', textAlign: 'center', fontSize: '18px' }}>useId - Rejestracja załogi</h1>
        <p style={{ color: '#778da9', textAlign: 'center', fontSize: '13px', marginBottom: '20px' }}>
          Każda instancja formularza ma unikalne ID generowane przez useId
        </p>

        <div style={{ display: 'grid', gap: '16px' }}>
          {Array.from({ length: formCount }, (_, i) => (
            <CrewMemberForm key={i} title={'Członek załogi #' + (i + 1)} />
          ))}

          <MissionPrioritySelector />
        </div>

        <div style={{ display: 'flex', gap: '8px', justifyContent: 'center', marginTop: '16px' }}>
          <button
            onClick={() => setFormCount(c => c + 1)}
            style={{ padding: '8px 16px', borderRadius: '8px', border: '1px solid #00d4ff', background: 'transparent', color: '#00d4ff', cursor: 'pointer' }}
          >
            + Dodaj formularz
          </button>
          {formCount > 1 && (
            <button
              onClick={() => setFormCount(c => c - 1)}
              style={{ padding: '8px 16px', borderRadius: '8px', border: '1px solid #ff6b6b', background: 'transparent', color: '#ff6b6b', cursor: 'pointer' }}
            >
              - Usuń ostatni
            </button>
          )}
        </div>

        <div style={{ marginTop: '16px', background: '#1b2838', padding: '12px', borderRadius: '8px', border: '1px solid #415a77' }}>
          <h4 style={{ color: '#778da9', margin: '0 0 8px', fontSize: '12px' }}>Dlaczego useId zamiast Math.random()?</h4>
          <ul style={{ color: '#e0e1dd', fontSize: '12px', margin: 0, paddingLeft: '20px', lineHeight: '1.8' }}>
            <li><span style={{ color: '#00ff88' }}>SSR/SSG</span> - te same ID na serwerze i kliencie</li>
            <li><span style={{ color: '#00d4ff' }}>Dostępność</span> - stabilne htmlFor/id/aria-describedby</li>
            <li><span style={{ color: '#ffaa00' }}>Wielokrotne instancje</span> - każda ma unikalne ID</li>
            <li><span style={{ color: '#ff6b6b' }}>Hydratacja</span> - brak niezgodności po stronie przeglądarki</li>
          </ul>
        </div>
      </div>
    </div>
  );
}

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. Główny cel useCallback to:

  2. 2. Jaka jest główna różnica między useMemo a useCallback?

To 2 z 3 pytań do tej lekcji. Pozostałe rozwiążesz w grze.

Zadania praktyczne w grze

  • Edytor kodu

    W pliku App.jsx jest katalog ośmiu planet z polem wyszukiwania, listą sortowania i przyciskiem „Sygnał radiowy”, który zmienia inny stan. Funkcja filterPlanets udaje kosztowne obliczenie i przy każdym wywołaniu wypisuje komunikat w konsoli. Uzupełnij luki: ___BLANK1___ to hook, który zapamiętuje wynik obliczenia między renderami, a ___BLANK2___ to zmienne stanu, od których zależy wynik (lista zależności). Wpisanie tekstu i zmiana sortowania mają przeliczyć listę, a kliknięcie „Sygnał radiowy” już nie. Sprawdź w konsoli podglądu, kiedy pojawia się komunikat.

  • Klikanie w kolejności

    Ułóż składnię hooka useMemo do memoizacji kosztownych obliczeń:

  1. PytanieuseCallback
  2. Zadanie z kodemPraktyka: useMemo dla filtrowania danych
  3. PytanieRóżnica między useMemo a useCallback
  4. PytaniePrzedwczesna optymalizacja w React
  5. Kliknij w kolejnościSkładnia useMemo

Przydatne artykuły