o3-2025-04-16· OpenAI
LMArena Human Preference 140K
potrzebuję cheatsheet z reacta
- User
potrzebuję cheatsheet z reacta
- 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
Termin Opis krótki JSX Rozszerzenie składni JS ⇒ HTMLw JS.Komponent Funkcja lub klasa zwracająca JSX. Props Dane wejściowe (read-only). State Prywatne, mutowalne dane komponentu. Hook Funkcja zaczynająca się od use*, dodaje logikę w funkcjach.Virtual DOM Lekka 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 –
useStateimport { 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 –
useEffectimport { 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
Hook Co 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-domimport { 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 jestimport { 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
Kategoria Popularne libki Global state Redux Toolkit, Zustand, Jotai, Recoil Stylowanie styled-components, Emotion, TailwindCSS Forms React Hook Form, Formik, Zod Data-Fetching React Query, SWR, Apollo Client Animacje Framer Motion, React Spring
16. Debug & devtools
- React Developer Tools (Chrome/Firefox).
- Profiler zakładka “⚛ Profiler”.
- 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
- Oficjalna: https://react.dev
- Hooks FAQ: https://react.dev/reference/react
- Router: https://reactrouter.com
- Tailwind + React: https://tailwindcss.com/docs/guides/vite
🚀 TL;DR
- Komponenty funkcyjne + Hooks to „nowy standard”.
useState&useEffect≈ 80 % codziennej pracy.- Optymalizuj dopiero gdy wystąpi problem.
- TypeScript + ESLint + Prettier = szczęśliwy dev.
- Czytaj oficjalny docs – został całkowicie przepisany w 2023 r.!
Powodzenia i miłego kodzenia! 🧑💻
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.