Skip to content
TheChatArchiveThe Chat Archive
o3-2025-04-16· OpenAIHugging Face LMArena Human Preference 140K

potrzebuję cheatsheet z reacta

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Qwenqwq-32b’s answer.
  1. User

    potrzebuję cheatsheet z reacta

  2. Assistant

    📘 React Cheat-Sheet (PL)

    Szybka ściąga z najczęściej używanych API, wzorców i narzędzi Reacta (v18+).
    Wszystkie przykłady w ES6+ i w formie komponentów funkcyjnych.


    1. Podstawowe pojęcia

    TerminOpis krótki
    JSXRozszerzenie składni JS ⇒ HTML w JS.
    KomponentFunkcja lub klasa zwracająca JSX.
    PropsDane wejściowe (read-only).
    StatePrywatne, mutowalne dane komponentu.
    HookFunkcja zaczynająca się od use*, dodaje logikę w funkcjach.
    Virtual DOMLekka reprezentacja UI w pamięci.

    2. Tworzenie projektu

    # npm
    npm create vite@latest my-app --template react
    npm i
    npm run dev
    
    # lub CRA
    npx create-react-app my-app
    

    3. Komponent funkcyjny + props

    function Hello({ name = 'Świecie' }) {
      return <h1>Cześć, {name}! 👋</h1>;
    }
    

    Użycie:

    <Hello name="Asia" />
    

    4. State – useState

    import { useState } from 'react';
    
    function Counter() {
      const [count, setCount] = useState(0);      // [wartość, setter]
    
      return (
        <>
          <p>Wynik: {count}</p>
          <button onClick={() => setCount(prev => prev + 1)}>+1</button>
        </>
      );
    }
    

    5. Efekty uboczne – useEffect

    import { useEffect, useState } from 'react';
    
    function Users() {
      const [users, setUsers] = useState([]);
    
      useEffect(() => {
        fetch('/api/users')
          .then(res => res.json())
          .then(setUsers);
      }, []); // [] ⇒ wykona się raz po montażu
    
      return users.map(u => <p key={u.id}>{u.name}</p>);
    }
    

    Czyszczenie:

    useEffect(() => {
      const id = setInterval(() => console.log('tick'), 1000);
      return () => clearInterval(id); // unmount / dependency-change
    }, []);
    

    6. Pozostałe popularne hooki

    HookCo robi / Kiedy użyć?
    useContext(ctx)Dostęp do wartości z Context API.
    useReducer(r,i)Złożony state (Redux-like).
    useMemo(fn,[d])Cache wartości obliczeniowych.
    useCallback(f,[d])Cache referencji funkcji (opt. rendu).
    useRef(init)Mutable ref, dostęp do DOM (ref.current).
    useLayoutEffectJak useEffect, ale synchronicznie po DOM.

    7. Context API – globalny state light

    const ThemeCtx = React.createContext('light');
    
    function App() {
      const [theme, setTheme] = useState('light');
      return (
        <ThemeCtx.Provider value={{ theme, setTheme }}>
          <Toolbar />
        </ThemeCtx.Provider>
      );
    }
    
    function Toolbar() {
      const { theme, setTheme } = useContext(ThemeCtx);
      return (
        <button onClick={() => setTheme(t => t === 'light' ? 'dark' : 'light')}>
          Aktualny motyw: {theme}
        </button>
      );
    }
    

    8. Routing (React Router v6)

    npm i react-router-dom
    
    import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
    
    function App() {
      return (
        <BrowserRouter>
          <nav>
            <Link to="/">Home</Link> | <Link to="/about">O nas</Link>
          </nav>
    
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/about" element={<About />} />
            <Route path="*" element={<h2>404</h2>} />
          </Routes>
        </BrowserRouter>
      );
    }
    

    9. Formularze i kontrolowane pola

    function Login() {
      const [form, setForm] = useState({ email: '', pass: '' });
    
      const handleChange = e =>
        setForm({ ...form, [e.target.name]: e.target.value });
    
      const handleSubmit = e => {
        e.preventDefault();
        console.log(form); // wysyłka
      };
    
      return (
        <form onSubmit={handleSubmit}>
          <input name="email" value={form.email} onChange={handleChange} />
          <input name="pass"  value={form.pass}  onChange={handleChange} type="password"/>
          <button>Zaloguj</button>
        </form>
      );
    }
    

    10. Lifting state up

    Wspólna wartość w rodzicu:

    function Parent() {
      const [color, setColor] = useState('red');
      return (
        <>
          <Picker onPick={setColor} />
          <Box color={color} />
        </>
      );
    }
    

    11. Optymalizacja renderu

    • React.memo(Component) – płytkie porównanie props.
    • useCallback & useMemo – pamiętanie referencji.
    • Lazy loading:

    const Settings = React.lazy(() => import('./Settings'));
    
    <Suspense fallback={<Spinner/>}>
      <Settings />
    </Suspense>
    

    12. Portale & modale

    import { createPortal } from 'react-dom';
    
    function Modal({children}) {
      return createPortal(
        <div className="overlay">{children}</div>,
        document.getElementById('modal-root')
      );
    }
    

    13. Testowanie (React Testing Library)

    npm i -D @testing-library/react jest
    
    import { render, screen, fireEvent } from '@testing-library/react';
    import Counter from './Counter';
    
    test('inkrementuje wartość', () => {
      render(<Counter />);
      fireEvent.click(screen.getByText('+1'));
      expect(screen.getByText(/Wynik: 1/)).toBeInTheDocument();
    });
    

    14. TypeScript (quick glance)

    type Props = { msg: string };
    
    const Hello: React.FC<Props> = ({ msg }) => <p>{msg}</p>;
    

    tsconfig.json ⇒ "jsx": "react-jsx" (React 17+).


    15. Ekosystem w pigułce

    KategoriaPopularne libki
    Global stateRedux Toolkit, Zustand, Jotai, Recoil
    Stylowaniestyled-components, Emotion, TailwindCSS
    FormsReact Hook Form, Formik, Zod
    Data-FetchingReact Query, SWR, Apollo Client
    AnimacjeFramer Motion, React Spring

    16. Debug & devtools

    1. React Developer Tools (Chrome/Firefox).
    2. Profiler zakładka “⚛ Profiler”.
    3. StrictMode wykrywa niebezpieczne patterny.

    17. Przydatne snippet-y

    // Bezpieczne odwołanie async w efekcie
    useEffect(() => {
      let isMounted = true;
      fetch('/data').then(r => r.json()).then(d => {
        if (isMounted) setData(d);
      });
      return () => (isMounted = false);
    }, []);
    
    // Forwarding ref
    const Input = React.forwardRef((props, ref) => (
      <input ref={ref} {...props} />
    ));
    

    18. Linki do dokumentacji


    🚀 TL;DR

    1. Komponenty funkcyjne + Hooks to „nowy standard”.
    2. useState & useEffect ≈ 80 % codziennej pracy.
    3. Optymalizuj dopiero gdy wystąpi problem.
    4. TypeScript + ESLint + Prettier = szczęśliwy dev.
    5. Czytaj oficjalny docs – został całkowicie przepisany w 2023 r.!

    Powodzenia i miłego kodzenia! 🧑‍💻

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.

Identical first prompt