React Hooks Components

Comprehensive examples of React hooks with interactive demos, from basic state management to advanced patterns

Basic Hooks

Essential React hooks for state management, side effects, and performance optimization

Basic React Hooks

Essential React hooks for managing state, side effects, and performance optimization

useState

The most basic hook for managing component state

Counter Example

Simple state management with useState

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

return (
  <div>
    <p>Count: {count}</p>
    <button onClick={() => setCount(count + 1)}>
      Increment
    </button>
  </div>
);

Text Input State

Managing text input with controlled components

Hello, Anonymous!

const [name, setName] = useState("");

return (
  <input
    value={name}
    onChange={(e) => setName(e.target.value)}
    placeholder="Enter your name..."
  />
);

useEffect

Hook for side effects like timers, API calls, and subscriptions

Timer with useEffect

Creating a timer that updates every second

00:00
Status: Stopped
const [timer, setTimer] = useState(0);
const [isRunning, setIsRunning] = useState(false);

useEffect(() => {
  let interval;
  if (isRunning) {
    interval = setInterval(() => {
      setTimer(timer => timer + 1);
    }, 1000);
  }
  return () => clearInterval(interval);
}, [isRunning]);

useCallback

Optimize performance by memoizing callback functions

Todo List with useCallback

Preventing unnecessary re-renders with memoized callbacks

Learn React Hooks
Build awesome apps
Share knowledge
Total: 3 todos
const addTodo = useCallback((todo) => {
  setTodos(prev => [...prev, todo]);
}, []);

const removeTodo = useCallback((index) => {
  setTodos(prev => prev.filter((_, i) => i !== index));
}, []);

useMemo

Optimize performance by memoizing expensive calculations

Expensive Calculation

Memoizing expensive computations to prevent unnecessary recalculations

1
2
3
4
5

Calculated Result: 30

Check console for memoization logs

const expensiveCalculation = useMemo(() => {
  console.log("Computing expensive calculation...");
  return numbers.reduce((sum, num) => sum + (num * multiplier), 0);
}, [numbers, multiplier]);

useRef

Access DOM elements and persist values across renders

Focus Management

Using useRef to directly manipulate DOM elements

Focus count: 0

The focus count persists across renders without causing re-renders

const inputRef = useRef(null);
const [focusCount, setFocusCount] = useState(0);

const focusInput = () => {
  inputRef.current?.focus();
  setFocusCount(prev => prev + 1);
};

return (
  <input ref={inputRef} />
);

Interactive Hooks

Advanced hooks with complex interactions, real-time updates, and context management

Interactive React Hooks

Advanced hooks with complex interactions, real-time updates, and context management

useReducer

Manage complex state logic with reducer pattern

Advanced Counter with History

Complex state management with actions and history tracking

0
Step:

History (0 actions):

const [state, dispatch] = useReducer(counterReducer, {
  count: 0,
  step: 1,
  history: []
});

function counterReducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {
        ...state,
        count: state.count + state.step,
        history: [...state.history, state.count]
      };
    // ... other cases
  }
}

useContext

Share data across components without prop drilling

Theme Provider

Global theme management using Context API

Current Theme: light

This theme state is managed by useContext and shared across the entire component tree without prop drilling!

const ThemeContext = createContext();

function useTheme() {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within ThemeProvider');
  }
  return context;
}

function ThemeConsumer() {
  const { theme, setTheme } = useTheme();
  return <div>Current theme: {theme}</div>;
}

Advanced useEffect

Complex side effects with real-time updates and cleanup

Download Manager

Real-time progress tracking with multiple downloads

No downloads yet. Start one to see the progress!
useEffect(() => {
  const interval = setInterval(() => {
    setDownloads(prev => prev.map(download => {
      if (download.status === 'downloading' && download.progress < 100) {
        const newProgress = Math.min(download.progress + Math.random() * 10, 100);
        return {
          ...download,
          progress: newProgress,
          status: newProgress === 100 ? 'completed' : 'downloading'
        };
      }
      return download;
    }));
  }, 500);

  return () => clearInterval(interval);
}, []);

useLayoutEffect

Synchronous DOM measurements and updates

Activity Tracker

Real-time mouse tracking and user activity monitoring

Live Activity Tracker

Mouse: (0, 0)

Recent Activities:

Move your mouse and click to see activities!

useLayoutEffect(() => {
  const handleMouseMove = (e) => {
    setMousePosition({ x: e.clientX, y: e.clientY });
  };

  const handleClick = () => {
    setActivities(prev => [
      { action: `Clicked at (${mousePosition.x}, ${mousePosition.y})`, timestamp: Date.now() },
      ...prev.slice(0, 9)
    ]);
  };

  document.addEventListener('mousemove', handleMouseMove);
  document.addEventListener('click', handleClick);

  return () => {
    document.removeEventListener('mousemove', handleMouseMove);
    document.removeEventListener('click', handleClick);
  };
}, [mousePosition]);

Advanced Hooks

Custom hooks, performance optimization, and enterprise-grade patterns for complex applications

Advanced React Hooks

Custom hooks, performance optimization, and enterprise-grade patterns for complex applications

Custom Hooks

Reusable stateful logic with custom hook patterns

useDebounce Hook

Debounce user input to prevent excessive API calls

Immediate:

Empty

Debounced (500ms):

Empty

function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => clearTimeout(handler);
  }, [value, delay]);

  return debouncedValue;
}

useLocalStorage Hook

Persistent state management with localStorage

theme
notifications
auto Save
Data is automatically saved to localStorage and persists across browser sessions.
function useLocalStorage(key, initialValue) {
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      return initialValue;
    }
  });

  const setValue = (value) => {
    try {
      setStoredValue(value);
      window.localStorage.setItem(key, JSON.stringify(value));
    } catch (error) {
      console.error('Error setting localStorage:', error);
    }
  };

  return [storedValue, setValue];
}

useImperativeHandle

Expose imperative APIs to parent components

Custom Input with Imperative API

Access child component methods through refs

const CustomInput = forwardRef((props, ref) => {
  const [value, setValue] = useState('');
  const inputRef = useRef();

  useImperativeHandle(ref, () => ({
    focus: () => inputRef.current.focus(),
    getValue: () => value,
    setValue: (newValue) => setValue(newValue)
  }));

  return <input ref={inputRef} value={value} onChange={e => setValue(e.target.value)} />;
});

Enterprise Patterns

Real-world patterns for complex applications

Performance Monitoring

Custom hooks for performance tracking and analytics

Component Renders

1,234

Memory Usage

45.2MB

Load Time

1.2s

Performance Insights

Largest Contentful Paint
2.1s
First Input Delay
45ms
Cumulative Layout Shift
0.15
function usePerformanceMonitor() {
  const [metrics, setMetrics] = useState({});
  
  useEffect(() => {
    const observer = new PerformanceObserver((list) => {
      const entries = list.getEntries();
      setMetrics(prev => ({
        ...prev,
        ...processEntries(entries)
      }));
    });
    
    observer.observe({ entryTypes: ['navigation', 'paint', 'largest-contentful-paint'] });
    
    return () => observer.disconnect();
  }, []);
  
  return metrics;
}