React / Compiler / React 19

    React Compiler i React 19

    Automatyczna memoizacja (bez useMemo/useCallback), eslint-plugin-react-compiler, React 19 (use hook, useActionState, Server Actions, ref jako prop).

    Compiler
    Auto memo
    use()
    Async hook
    useActionState
    Form state
    Server Actions
    RPC bez API

    6 funkcji React Compiler i React 19

    Automatyczna memoizacja, eslint, use(), useActionState, Server Actions i ref prop — co robi, jak działa i wymagania.

    Feature Działa Wymagania
    Automatyczna memoizacja Tak (bez useMemo/useCallback) Rules of React — brak mutacji props
    eslint-plugin-react-compiler Linting naruszeń ESLint 8+, npm install plugin
    use(promise) Async w warunkach React 19, Suspense boundary powyżej
    useActionState Form state + isPending React 19 lub useFormState (React 18)
    Server Actions RPC bez API route React 19 + bundler (Next.js, Remix)
    ref jako prop Bez forwardRef React 19 — stare forwardRef deprecated

    Często zadawane pytania

    Co to jest React Compiler i jak automatycznie memoizuje?

    React Compiler (dawniej React Forget): nowe narzędzie Facebooka. Automatyczna memoizacja — bez useMemo i useCallback. Kompilator analizuje kod. Dodaje memoizację tam gdzie potrzeba. Wynik: mniej boilerplate, ta sama wydajność. Jak działa: Kompilator czyta Components i hooks. Analizuje zależności. Wstawia cache calls automatycznie. Analogia: jak TypeScript ale dla memoizacji. Bez kompilatora: const value = useMemo(() => expensiveCalc(a, b), [a, b]). const handler = useCallback(() => handleClick(id), [id]). Z kompilatorem (taki sam wynik): const value = expensiveCalc(a, b). const handler = () => handleClick(id). Kompilator sam to optymalizes. Instalacja (React 19): npm install --save-dev babel-plugin-react-compiler. babel.config.js: plugins: [['babel-plugin-react-compiler', {target: '18'}]]. Lub Vite: import ReactCompilerConfig from 'babel-plugin-react-compiler'. vite.config.ts: react({babel: {plugins: [['babel-plugin-react-compiler', ReactCompilerConfig]]}}). Wymagania: React 17+ (instrukcja). React 19 dla pełnego wsparcia. TypeScript lub JavaScript. Kod musi spełniać Rules of React. Rules of React: komponenty i hooks to czyste funkcje. Nie mutuj props. Nie czytaj/pisz refs podczas renderowania. Brak side effects w render. Kompilator egzekwuje te reguły.

    eslint-plugin-react-compiler — wykrywanie naruszeń Rules of React?

    eslint-plugin-react-compiler: ESLint plugin od React team. Wykrywa naruszenia Rules of React. Działa bez kompilatora. Przygotuj kod na kompilator. Instalacja: npm install --save-dev eslint-plugin-react-compiler. .eslintrc: plugins: ['react-compiler']. rules: {'react-compiler/react-compiler': 'error'}. Co wykrywa: Mutacje props i state. Czytanie ref.current w render. Dostęp do zewnętrznych zmiennych bez deklaracji w deps. Warunki w hookach. Przykład naruszenia: function BadComponent({items}) { items.push(newItem) // mutacja props! return ul... }. ESLint: react-compiler/react-compiler: Mutating a value returned from props is not allowed. Naprawienie: const localItems = [...items, newItem]. Granularność: 'use no memo' — wyłącz kompilator per komponent. Pomocne podczas migracji. Debugowanie: React DevTools (nowe) — pokaż co skompilowane. Komponent outline. Które props zmemoizowane. Opt-in (React 17/18): 'use memo' — wymuś kompilację per plik. Stopniowa migracja. Bez zmiany całej aplikacji. Compatibility: hooks bez naruszenia reguł — kompilowane automatycznie. Klasy — nie kompilowane (brak hooks). HOC z refs — może wymagać naprawy. forwardRef — wspierany. React.memo — kompilator może usunąć zbędne. Nie wszystkie wzorce obsługiwane: useImperativeHandle złożone wzorce. Custom hooks z mutacjami.

    React 19 — nowe funkcje: use hook, useActionState i Server Actions?

    use(promise): nowy hook dla async. Suspense integration wbudowana. const data = use(fetchData()). Działa w warunkach (if). Nie tylko na top level. use(context): alternatywa dla useContext. Działa z resolving resources. Suspense boundary wymagane powyżej. useActionState (dawniej useFormState): const [state, dispatch, isPending] = useActionState(action, initialState). action — async function (Server Action lub zwykła). isPending — boolean podczas wykonania. Automatyczny error handling. useFormStatus: status formularza bez prop drilling. W child komponencie. const {pending, data, method} = useFormStatus(). Bez React Context. useOptimistic: const [optimisticItems, addOptimistic] = useOptimistic(items, updater). addOptimistic(newItem). Rollback automatyczny po Server Action. React.use(): łączony z Suspense. const resource = createResource(fetchUser). function Profile() { const user = React.use(resource) }. Server Actions (React 19 + Next.js 15): 'use server' directive. async function createPost(formData: FormData) {'use server'. await db.post.create({data: {...formData}})}. form action={createPost}. Bez API route. RPC przez HTTP automatycznie. Serializable arguments only. Error handling: try/catch w Server Action. return {error: message}. useActionState pobierze błąd. ref as prop (React 19): forwardRef nie potrzebny. function Input({ref, ...props}) — ref jako zwykły prop. Uproszczone forwarding. Context jako provider: Context value={...} zamiast Context.Provider.

    Migracja i kompatybilność React Compiler?

    Stopniowa migracja: Włącz eslint-plugin-react-compiler. Napraw naruszenia. Włącz kompilator per plik ('use memo'). Sprawdź wyniki (React DevTools). Włącz globalnie. Typowe naruszenia do naprawy: Mutacje obiektów: const arr = []. arr.push(item). Napraw: return [...arr, item]. Czytanie mutable ref w render: el.current.style. Napraw: przenieś do effect. Warunki w hookach (już naruszenie Rules): if (cond) useState(). Napraw: zawsze call hooks. Zewnętrzne zmienne: let count = 0. function Component() { count++ }. Napraw: useState. Custom hooks z naruszeniami: useWindowSize z mutable state poza hooks. Napraw: useState wewnątrz. React DevTools dla kompilatora: Nowe React DevTools pokazują memo status. Zielona obwódka — skompilowane i memoizowane. Memo badge na komponentach. Profiler — porównaj przed i po. Testowanie zmian: Nie zakładaj że kompilator zawsze pomaga. Testuj wydajność. Benchmark krytyczne ścieżki. react-scan — wizualizuj re-renders. Performance: Kompilator generuje dodatkowy kod (cache checks). Narzut na pierwsze renderowanie. Korzyści przy re-renderach. Nie silver bullet dla każdego. React.memo() po kompilatorze: Kompilator może eliminować zbędne React.memo. Lub je uzupełniać automatycznie. Nie usuwaj ręcznie bez sprawdzenia. Inne memoizacje (Zustand, Jotai): Selektory — kompilator nie optymalizuje. useSelector w Redux — nie zmienione. Tylko React rendering zoptymalizowane.

    React 19 i Compiler — production readiness i best practices?

    Status (2024): React Compiler — beta (Open Source). Używany przez Instagram prod (Facebook). Nie wszystkie wzorce. Production ready: nie dla wszystkich projektów. React 19 — stable release. Breaking changes: act() deprecation (testy). ref cleanup functions. hydration error diffs. useDeferredValue initialValue. Context bez .Provider. Nowe błędy hydration: React 19 lepsze hydration error messages. Pokaż diff HTML. Łatwiejsze debugowanie. Document metadata (React 19): title, meta, link z komponentów. Automatyczne hoisting do head. Bez react-helmet. Resource preloading: preload, prefetch, preinit APIs. Inline in components. Automatyczny head management. Best practices z kompilatorem: Nie myśl o memoizacji — pisz czysty kod. Kompilator zoptymalizuje. Skupiaj się na Rules of React. Używaj TypeScript dla lepszego inference. Stopniowa adopcja: Nie migruj całości naraz. Per page, per route. Testuj regressions. Rollback per komponent ('use no memo'). Ecosystem: Next.js 15 — pierwsza klasa wsparcia kompilatora. Remix — w trakcie. Vite + React — przez babel plugin. CRA — deprecated (użyj Vite). Monitoring: React DevTools Profiler. Porównaj renders przed/po. Core Web Vitals mierz w prod. LCP improvement — główny benefit. Unikaj: Poleganie na memoizacji zamiast naprawy architektury. Kompilator nie naprawia złej architektury. Ekstremalne optymalizacje — zajmij się DX.

    Czytaj dalej

    Powiązane artykuły

    Kontakt

    Skontaktuj się z nami

    Porozmawiajmy o Twoim projekcie. Bezpłatna wycena w ciągu 24 godzin.

    Wyślij zapytanie

    Bezpłatna wycena w 24h
    Bez zobowiązań
    Indywidualne podejście
    Ekspresowa realizacja

    Telefon

    +48 790 814 814

    Pon-Pt: 9:00 - 18:00

    Email

    adam@fotz.pl

    Odpowiadamy w ciągu 24h

    Adres

    Plac Wolności 16

    61-739 Poznań

    Godziny pracy

    Pon - Pt9:00 - 18:00
    Sob - NdzZamknięte

    Wolisz porozmawiać?

    Zadzwoń teraz i porozmawiaj z naszym specjalistą o Twoim projekcie.

    Zadzwoń teraz