What is React Hooks in React?

This article provides a clear and concise guide to React Hooks, explaining what they are, why they were introduced, and how they function in modern web development. You will learn about core hooks like useState and useEffect, the key benefits they offer over traditional class components, and the essential rules you must follow when implementing them in your React projects.

Understanding React Hooks

React Hooks are built-in functions introduced in React 16.8 that allow developers to use state and other React features in functional components. Before hooks, managing state or handling lifecycle events required writing class components. Hooks allow you to write your entire application using functional components, which simplifies the codebase and makes it more readable.

Why React Hooks Were Introduced

Prior to React 16.8, class components were the standard for managing stateful logic. However, class components came with several challenges: * Complex Code: Managing the this keyword in JavaScript can be confusing and error-prone. * Component Verbosity: Class components require a lot of boilerplate code, making them harder to write and maintain. * Difficult Logic Reuse: Sharing stateful logic between class components often required complex patterns like Higher-Order Components (HOCs) or render props.

Hooks solve these problems by allowing you to extract and reuse stateful logic without changing your component hierarchy, resulting in cleaner, more modular code.

Core React Hooks

While React offers several built-in hooks, two are used in almost every functional component:

1. The useState Hook

The useState hook allows you to add state to a functional component. It accepts the initial state as an argument and returns an array with two elements: the current state value and a function to update it.

import React, { useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

2. The useEffect Hook

The useEffect hook lets you perform side effects in functional components. Side effects include data fetching, manual DOM manipulations, and setting up subscriptions. It serves a similar purpose to the lifecycle methods componentDidMount, componentDidUpdate, and componentWillUnmount in class components.

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

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

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(prev => prev + 1);
    }, 1000);

    // Cleanup the interval on component unmount
    return () => clearInterval(interval);
  }, []); // Empty array means this effect runs once on mount

  return <p>Time elapsed: {seconds} seconds</p>;
}

Essential Rules of Hooks

To ensure hooks work correctly, React enforces two strict rules:

  1. Only Call Hooks at the Top Level: Do not call hooks inside loops, conditions, or nested functions. Always use them at the top level of your React function to ensure they execute in the same order on every render.
  2. Only Call Hooks from React Functions: You should only call hooks from React functional components or from custom hooks. Do not call them from regular JavaScript functions.