Understanding React Hooks

React Hooks were introduced in React 16.8 to allow functional components to manage state and side effects without needing class components. They simplify component logic and improve code readability.

Why Use Hooks?

  • Simplifies State Management: No need for class components.
  • Encapsulates Side Effects: useEffect manages effects in a clean way.
  • Improves Code Reusability: Custom hooks allow logic sharing.

Common React Hooks

useState

Used for managing local component state.

import { useState } from 'react';

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

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

useEffect

Handles side effects like data fetching or subscriptions.

import { useState, useEffect } from 'react';

function Timer() {
  const [time, setTime] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setTime((prevTime) => prevTime + 1);
    }, 1000);
    
    return () => clearInterval(interval);
  }, []);

  return <p>Elapsed time: {time} seconds</p>;
}

useContext

Provides an easier way to manage global state without prop drilling.

import { createContext, useContext } from 'react';

const ThemeContext = createContext('light');

function ThemeDisplay() {
  const theme = useContext(ThemeContext);
  return <p>Current theme: {theme}</p>;
}

Custom Hooks

You can create custom hooks to reuse logic across components.

import { useState, useEffect } from 'react';

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return width;
}