🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
Quick Reference

React.js

The modern guide to Hooks, State, and Component Architecture.

Functional Components

Basic Component Structure

React relies on functions that return JSX.

import React from 'react';

interface ButtonProps {
  label: string;
  onClick: () => void;
}

export default function Button({ label, onClick }: ButtonProps) {
  return (
    <button 
      onClick={onClick}
      className="bg-blue-500 text-white px-4 py-2"
    >
      {label}
    </button>
  );
}

Core Hooks

useState

Manage local component state.

import { useState } from 'react';

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

  // Using functional update for safety
  const increment = () => setCount(prev => prev + 1);

  return <button onClick={increment}>{count}</button>;
}

useEffect

Handle side effects like data fetching or subscriptions.

import { useEffect, useState } from 'react';

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    // Setup
    const interval = setInterval(() => setSeconds(s => s + 1), 1000);
    
    // Cleanup function runs on unmount
    return () => clearInterval(interval);
  }, []); // Empty array means run once on mount

  return <div>{seconds}s</div>;
}

Performance Hooks

useMemo & useCallback

Prevent unnecessary re-renders and re-calculations.

import { useMemo, useCallback } from 'react';

// Cache an expensive calculation
const expensiveResult = useMemo(() => {
  return items.filter(item => item.price > 100);
}, [items]); // Re-run only if items change

// Cache a function reference
const handleSubmit = useCallback(() => {
  submitData(expensiveResult);
}, [expensiveResult]); // Re-create only if expensiveResult changes

Context API

Global State Management

Avoid prop drilling by sharing state globally.

import { createContext, useContext, useState } from 'react';

const ThemeContext = createContext('light');

export function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('light');
  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

// Custom Hook consumption
export const useTheme = () => useContext(ThemeContext);

Rules of Hooks

Critical Guidelines

RuleReasoning
Only call at Top LevelDon't call inside loops, conditions, or nested functions to ensure correct hook ordering.
Only call in React FunctionsHooks must be called inside React functional components or custom hooks.
Include dependenciesAlways list all reactive variables in the dependency array (useEffect, useMemo).