React.js
React.js
Components, hooks, state management, routing, and best practices — your complete React reference.
📖 6 sections
⏰ 18 min read
✅ Quizzes included
01Components & JSX
REACTComponent basics
// Functional component (modern, preferred)
function Button({ label, onClick, disabled = false }) {
  return (
    
  );
}

// Usage
02useState & useEffect
REACTCore hooks
import { useState, useEffect } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  const [data, setData] = useState(null);

  // Fetch on mount
  useEffect(() => {
    fetch("/api/data")
      .then(r => r.json())
      .then(d => setData(d));
  }, []);  // [] = run once

  // Run when count changes
  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

  return (
    

{count}

); }
💡
Always use the functional form of setState when new state depends on old state: setCount(prev => prev + 1). Avoids stale closure bugs.
03More Hooks
REACTuseRef, useContext, useMemo, useCallback
// useRef: access DOM elements or persist values
const inputRef = useRef(null);

inputRef.current.focus();

// useContext: avoid prop drilling
const ThemeContext = createContext("light");
// Provider:

  

// Consumer:
const theme = useContext(ThemeContext);

// useMemo: memoize expensive calculations
const sorted = useMemo(() => items.sort(), [items]);

// useCallback: memoize functions
const handleClick = useCallback(() => {
  doSomething(id);
}, [id]);
❓ Quiz
What does the [] dependency array in useEffect mean?
Empty dependency array [] means the effect runs once after the initial render (componentDidMount equivalent). Omitting it runs every render.
04Lists, Events & Forms
REACTPatterns
// Lists: always need unique key prop
const items = ["Apple","Banana","Cherry"];
    {items.map((item, i) => (
  • {item}
  • // prefer unique id over index ))}
// Controlled form const [email, setEmail] = useState(""); setEmail(e.target.value)} /> // Conditional rendering {isLoading && } {error ? : } {user?.name ?? "Guest"} // optional chaining
05State Management
REACTContext & useReducer
// useReducer for complex state
const initialState = { count: 0, user: null };

function reducer(state, action) {
  switch(action.type) {
    case "INCREMENT": return {...state, count: state.count+1};
    case "SET_USER": return {...state, user: action.payload};
    default: return state;
  }
}

const [state, dispatch] = useReducer(reducer, initialState);
dispatch({ type: "INCREMENT" });
dispatch({ type: "SET_USER", payload: { name: "Ali" } });

// For global state: Zustand or Redux Toolkit
06React Router & Patterns
REACTRouting
import { BrowserRouter, Routes, Route, Link, useNavigate, useParams } from "react-router-dom";


  
  
    } />
    } />
    } />
    } />
  


// In component
const { id } = useParams();
const navigate = useNavigate();
navigate("/courses");