Sunday, November 16, 2025

What are Hooks?

 Hooks are special functions that allow functional components to use state, lifecycle methods, context, and other React features that were previously only available in class components.


Basic Rules of Hooks

Only Call Hooks at the Top Level


Don't call Hooks inside loops, conditions, or nested functions


Only Call Hooks from React Functions


Call them from React functional components or custom Hooks


Most Commonly Used Hooks

1. useState - State Management



import React, { useState } from 'react';


function Counter() {

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


  return (

    <div>

      <p>You clicked {count} times</p>

      <button onClick={() => setCount(count + 1)}>

        Click me

      </button>

    </div>

  );

}



2. useEffect - Side Effects

import React, { useState, useEffect } from 'react';


function UserProfile({ userId }) {

  const [user, setUser] = useState(null);


  // Similar to componentDidMount and componentDidUpdate

  useEffect(() => {

    // Fetch user data

    fetch(`/api/users/${userId}`)

      .then(response => response.json())

      .then(userData => setUser(userData));

  }, [userId]); // Only re-run if userId changes


  return <div>{user ? user.name : 'Loading...'}</div>;

}



How Hooks Work Internally

Hook Storage Mechanism

React maintains a linked list of Hooks for each component. When you call a Hook:


React adds the Hook to the list

On subsequent renders, React goes through the list in the same order

This is why Hooks must be called in the same order every render



Key Differences Between Hooks and Regular Functions

1. State Persistence Across Renders

Regular Function (state resets every call):


function regularCounter() {

  let count = 0; // Reset to 0 every time

  const increment = () => {

    count++;

    console.log(count);

  };

  return increment;

}


const counter1 = regularCounter();

counter1(); // Output: 1

counter1(); // Output: 1 (always starts from 0)



Hook (state persists between renders):


import { useState } from 'react';


function useCounter() {

  const [count, setCount] = useState(0); // Persists across re-renders

  

  const increment = () => {

    setCount(prev => prev + 1);

  };

  

  return [count, increment];

}


function Component() {

  const [count, increment] = useCounter();

  

  return (

    <button onClick={increment}>Count: {count}</button>

    // Clicking multiple times: 1, 2, 3, 4...

  );

}


Hook (proper lifecycle management):


import { useEffect, useState } from 'react';


function useTimer() {

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

  

  useEffect(() => {

    const interval = setInterval(() => {

      setSeconds(prev => prev + 1);

    }, 1000);

    

    // Cleanup function - runs on unmount

    return () => clearInterval(interval);

  }, []); // Empty dependency array = runs once

  

  return seconds;

}


function Component() {

  const seconds = useTimer();

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

  // Automatically cleans up when component unmounts

}





No comments:

Post a Comment