Skip to content

React Cheatsheet — Hooks & Patterns Quick Reference

DodaTech 3 min read

In this tutorial, you'll learn about React Cheatsheet. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

React hooks, JSX syntax, component patterns, props, state management, forms, event handling, and routing — a compact reference for daily React development.

JSX Syntax

// Must have single root element
return (
  <div className="container">
    <h1>{title}</h1>
    {isVisible && <p>shown</p>}
    <button onClick={handleClick}>Click</button>
  </div>
);

Component Basics

function Greeting({ name, age = 0 }) {       // props
  return <h1>Hello, {name}</h1>;
}

// children
function Layout({ children }) {
  return <div className="layout">{children}</div>;
}

useState

const [count, setCount] = useState(0);
const [user, setUser] = useState({ name: "", age: 0 });
setCount(c => c + 1);                    // functional update
setUser(prev => ({ ...prev, age: 30 })); // merge object

useEffect

useEffect(() => {
  fetch("/api/data").then(r => r.json()).then(setData);
  return () => cleanup();               // cleanup on unmount
}, []);                                 // [] = run once (mount)
// [id] = run when `id` changes
// no array = run on every render

useContext

const ThemeCtx = createContext("light");
// Provider:
<ThemeCtx.Provider value="dark"><App /></ThemeCtx.Provider>
// Consumer:
const theme = useContext(ThemeCtx);

useRef

const inputRef = useRef(null);
<input ref={inputRef} />;
inputRef.current.focus();   // access DOM

useReducer

const reducer = (state, action) => {
  switch (action.type) {
    case "inc": return { count: state.count + 1 };
    default: return state;
  }
};
const [state, dispatch] = useReducer(reducer, { count: 0 });
dispatch({ type: "inc" });

useMemo & useCallback

const sorted = useMemo(() => heavySort(list), [list]);
const handleClick = useCallback(() => doThing(id), [id]);
// Prevents unnecessary re-renders

Conditional Rendering

{isLoggedIn && <Dashboard />}
{isLoading ? <Spinner /> : <Data />}
{role === "admin" ? <AdminPanel /> : <UserPanel />}

Lists & Keys

{items.map(item => (
  <li key={item.id}>{item.name}</li>
))}

Forms

function MyForm() {
  const [val, setVal] = useState("");
  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(val);
  };
  return (
    <form onSubmit={handleSubmit}>
      <input value={val} onChange={e => setVal(e.target.value)} />
      <button type="submit">Send</button>
    </form>
  );
}

Event Handling

<button onClick={(e) => console.log(e.target)}>Click</button>
<input onChange={e => setVal(e.target.value)} />
<form onSubmit={handleSubmit}>...</form>

React Router (v6)

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

<BrowserRouter>
  <nav><Link to="/about">About</Link></nav>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/user/:id" element={<Profile />} />
    <Route path="*" element={<NotFound />} />
  </Routes>
</BrowserRouter>;

function Profile() {
  const { id } = useParams();
}

Custom Hooks

function useFetch(url) {
  const [data, setData] = useState(null);
  useEffect(() => {
    fetch(url).then(r => r.json()).then(setData);
  }, [url]);
  return data;
}
What is the difference between useState and useReducer?

useState is simpler — use it for independent state values (strings, numbers, booleans) or simple objects. useReducer is better for complex state logic involving multiple sub-values or when the next state depends on the previous one in non-trivial ways. Think of useReducer as useState with a reducer function for more predictable state transitions.

What is the purpose of the dependency array in useEffect?

The dependency array tells React when to re-run the effect. An empty array [] means the effect runs once after the initial render (mount). [id] means it re-runs whenever id changes. Omitting the array causes the effect to run after every render — usually a bug. React uses Object.is comparison to detect changes.

What is the difference between useMemo and useCallback?

useMemo memoizes a value (the result of a computation). useCallback memoizes a function (so it doesn't get recreated on every render). Internally, useCallback(fn, deps) is equivalent to useMemo(() => fn, deps). Use them to optimize child components that rely on reference equality to prevent unnecessary re-renders

See the full React tutorials for advanced patterns.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro