⚛️ React.js Modern
React.js Complete Cheatsheet
Hooks, components, state management — modern React from basics to advanced.
📖 10 sections
⏱ 20 min read
✅ Quizzes included
🌙 Dark mode
01 JSX Basics
JSXJSX syntax
// JSX = JavaScript + HTML-like syntax
const App = () => (
  
{/* class → className */}

Hello {name}

{/* JS expressions in {} */} img {/* self-closing */} {isLoggedIn && } {/* conditional */} {count > 0 ?

Positive

:

Zero

} {/* ternary */}
);
02 Components
JSXComponent types
// Functional (modern, use this)
const Button = ({ label, onClick }) => (
  
);

// With TypeScript props
interface Props { name: string; age?: number; }
const Card: React.FC = ({ name, age = 0 }) => (
  
{name} — {age}
); // Class component (legacy) class MyComp extends React.Component { render() { return
{this.props.name}
; } }
03 Props
JSXProps patterns
// Passing props


// Receiving props
const User = (props) => 

{props.name}

; const User = ({ name, age, isAdmin = false }) => (...); // destructure // Spreading props const btnProps = { onClick: fn, disabled: false };
💡
Always destructure props for cleaner code. Use defaultProps or default parameter values.
04 State & useState
JSXuseState hook
import { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);  // [state, setter]
  const [user, setUser] = useState({ name: 'Ali', age: 22 });
  const [items, setItems] = useState([]);

  // Always create new objects/arrays (don't mutate!)
  setUser({ ...user, age: 23 });          // update object
  setItems([...items, newItem]);          // add to array
  setItems(items.filter(i => i.id !== id)); // remove from array

  // Functional update (when new state depends on old)
  setCount(prev => prev + 1);

  return ;
};
05 useEffect
JSXuseEffect hook
import { useState, useEffect } from 'react';

const UserProfile = ({ userId }) => {
  const [user, setUser] = useState(null);

  // Runs after EVERY render
  useEffect(() => { document.title = 'App'; });

  // Runs ONCE (on mount)
  useEffect(() => { fetchData(); }, []);

  // Runs when userId changes
  useEffect(() => {
    async function loadUser() {
      const res = await fetch(`/api/users/${userId}`);
      const data = await res.json();
      setUser(data);
    }
    loadUser();
  }, [userId]);

  // Cleanup (runs on unmount)
  useEffect(() => {
    const timer = setInterval(fn, 1000);
    return () => clearInterval(timer);  // cleanup!
  }, []);
};
06 useContext
JSXuseContext — global state
// 1. Create context
const ThemeContext = createContext('light');

// 2. Provide context

  


// 3. Consume context (any depth, no prop drilling!)
const { theme, setTheme } = useContext(ThemeContext);

// For complex state: combine with useReducer
const [state, dispatch] = useReducer(reducer, initialState);
dispatch({ type: 'INCREMENT', payload: 1 });
07 Hooks Reference
useState
Local component state. Triggers re-render when called.
useEffect
Side effects: API calls, subscriptions, DOM updates.
useContext
Access context without prop drilling.
useReducer
Complex state logic. Alternative to useState.
useMemo
Memoize expensive calculations. `useMemo(() => compute(), [deps])`
useCallback
Memoize function reference. Prevents child re-renders.
useRef
Access DOM node or persist value without re-render.
Custom hooks
Extract stateful logic: `function useLocalStorage(key, init) {}`
💡
Custom hook names MUST start with 'use'. They can call other hooks.
08 Event Handling
JSXEvents & forms
// Event handling
09 Lists & Keys
JSXLists and keys
// Always use unique key on list items
const TodoList = ({ todos }) => (
  
    {todos.map(todo => (
  • {/* key must be unique + stable */} {todo.text}
  • ))}
); // Conditional rendering {isLoading && } {error && } {!isLoading && !error && }
⚠️
Never use array index as key if list can reorder/filter. Use unique ID from data.
10 Mini Quizzes
❓ Quiz 1
What does the useEffect dependency array control?
[] = run once on mount. [id] = run when id changes. No array = run after every render. Cleanup return function runs on unmount.
❓ Quiz 2
Why must React list items have a key prop?
Keys help React's reconciliation algorithm identify what changed, was added, or removed. Without keys, React re-renders the entire list.