React-Cheatsheet

👋 Hello React

// index.jsx
import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";

const root = createRoot(document.getElementById("root"));
root.render(<App />);

// App.jsx
export default function App() {
  return <h1>Hello, React!</h1>;
}

💡 Tip: Use Vite or Create React App to bootstrap quickly. Use createRoot for modern React rendering.

🧩 Components & JSX

// Functional component with JSX
function Greeting({ name }) {
  return <div>Hello, {name}!</div>;
}

// Usage
<Greeting name="Maxon" />

💡 Tip: Prefer functional components + hooks. JSX compiles to React.createElement().

📦 Props & State

import { useState } from "react";

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

💡 Tip: Props are read-only; state is local and mutable via setters. Lift state up for shared data.

🎯 Events

function Form() {
  const handleSubmit = (e) => {
    e.preventDefault();
    console.log("Submitted");
  };

  return <form onSubmit={handleSubmit}><button type="submit">Send</button></form>;
}

💡 Tip: React events are synthetic and camelCased (onClick, onChange).

🔀 Conditional Rendering

// Ternary
{isLoading ? <Loader /> : <Content />}

// Short-circuit
{items.length && <List items={items} />}

💡 Tip: For complex conditions prefer small components or helper functions for readability.

🔢 Lists & Keys

const items = ["a","b","c"];
return (
  <ul>
    {items.map((item, idx) => <li key={item}>{item}</li>)}
  </ul>
);

💡 Tip: Use stable unique keys (ids). Avoid array index as key for dynamic lists.

📝 Forms (Controlled)

import { useState } from "react";

function Login() {
  const [email, setEmail] = useState("");
  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(email);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input value={email} onChange={e => setEmail(e.target.value)} />
      <button type="submit">Login</button>
    </form>
  );
}

💡 Tip: For large forms consider libraries: React Hook Form or Formik for better performance and validation.

⏳ Effects & Lifecycle (useEffect)

import { useEffect } from "react";

useEffect(() => {
  // run once on mount
  fetchData();

  return () => {
    // cleanup on unmount
    cancelSubscription();
  };
}, []); // dependencies control when effect runs

💡 Tip: Keep effects focused; avoid heavy logic inside useEffect — extract to functions.

🧠 Refs, Memo & Callbacks

import { useRef, useMemo, useCallback } from "react";

const inputRef = useRef(null);
inputRef.current?.focus();

const expensive = useMemo(() => compute(value), [value]);
const onClick = useCallback(() => doSomething(id), [id]);

💡 Tip: Use useMemo/useCallback sparingly for expensive calcs or stable references.

🌐 Context API

import { createContext, useContext } from "react";

const ThemeContext = createContext("light");

function App() {
  return <ThemeContext.Provider value="dark"><Toolbar /></ThemeContext.Provider>;
}

function Toolbar() {
  const theme = useContext(ThemeContext);
  return <div className={theme}>Toolbar</div>;
}

💡 Tip: Use context for global settings, not for frequent local updates (can cause re-renders).

🚦 Routing (react-router)

import { BrowserRouter, Routes, Route, Link } from "react-router-dom";

function App() {
  return (
    <BrowserRouter>
      <nav><Link to="/">Home</Link></nav>
      <Routes>
        <Route path="/" element=<Home /> />
        <Route path="/about" element=<About /> />
      </Routes>
    </BrowserRouter>
  );
}

💡 Tip: Use nested routes and useNavigate for programmatic navigation.

📡 Data Fetching

// basic fetch with useEffect
useEffect(() => {
  let cancelled = false;
  fetch("/api/data")
    .then(res => res.json())
    .then(data => !cancelled && setData(data));
  return () => { cancelled = true; };
}, []);

// Recommended: use React Query / SWR for caching & revalidation

💡 Tip: Use libraries (React Query, SWR) for caching, background updates, and retries.

⚖️ State Management

// Local: useState, useReducer
const [state, dispatch] = useReducer(reducer, initialState);

// Global: Redux Toolkit (recommended)
import { configureStore, createSlice } from "@reduxjs/toolkit";

💡 Tip: Use local state for UI, Context for app config, and Redux/RTK or Zustand for large global state needs.

🎨 Styling

// CSS Modules
import styles from "./Button.module.css";
<button className={styles.primary}>Click</button>

// styled-components
import styled from "styled-components";
const Btn = styled.button`padding: 8px;`;

💡 Tip: Choose a consistent styling strategy: CSS modules, Tailwind, styled-components, or plain CSS.

⚡ Performance

import { memo } from "react";

const PureItem = memo(function Item({ value }) {
  return <div>{value}</div>;
});

// virtualization for long lists: react-window / react-virtualized

💡 Tip: Avoid unnecessary re-renders. Use memo, virtualization, and optimize context usage.

🧪 Testing

// React Testing Library + Jest
import { render, screen } from "@testing-library/react";
test("renders hello", () => {
  render(<Greeting name="Maxon" />);
  expect(screen.getByText(/hello/i)).toBeInTheDocument();
});

💡 Tip: Test behaviour, not implementation. Use MSW for mocking network requests.

🔧 Build & Tooling

// Vite (recommended)
npm create vite@latest my-app -- --template react

// Common scripts
npm run dev
npm run build
npm run preview

💡 Tip: Prefer Vite for faster dev server; configure bundler, linting, and type checking (TS) for production readiness.

🚀 Deployment

// Deploy options
Vercel, Netlify, Cloudflare Pages, AWS S3 + CloudFront

// Example: build & deploy
npm run build
// upload 'dist' (Vite) or 'build' (CRA) to static host

💡 Tip: Configure proper caching, asset hashing, and an index fallback for SPA routing (redirects/rewrite).

🧾 TypeScript

type Props = { name: string };

function Hello({ name }: Props) {
  return <div>Hello, {name}</div>;
}

💡 Tip: Use TypeScript for type-safety. Prefer typed hooks and avoid any where possible.

💡 Misc Tips

- Keep components small and focused
- Extract custom hooks for reuse (useFetch, useAuth)
- Avoid prop drilling: use context or state management
- Use ESLint + Prettier + TypeScript to keep code consistent

💡 Tip: Incrementally adopt best practices — start with small improvements like linting and type checks.

Post a Comment