React Hooks: Revolutionizing Functional Components

React Hooks: Revolutionizing Functional Components

On June 20, 2024, Posted by , In Reactjs, With Comments Off on React Hooks: Revolutionizing Functional Components
What are react hooks, how to create react js hooks with real time example

Table of Contents

React Hooks, introduced in React 16.8, have fundamentally transformed how we build React applications. Before Hooks, functional components were limited, often requiring the use of class components for more complex logic involving state and lifecycle methods. Hooks have changed this, enabling functional components to harness these features, leading to cleaner, more concise code. This article explores the world of React Hooks, their significance, and how they are used to enhance the functional components in React.

What are React Hooks?

React Hooks are functions that allow you to use state and other React features in functional components. Introduced in React 16.8, hooks enable developers to utilize state management, lifecycle methods, and side effects within functional components, which were previously only available in class components. Common hooks include useState for managing state, useEffect for handling side effects, and useContext for accessing context. Hooks simplify component logic, make code more reusable, and improve the overall readability and maintainability of React applications.

When to use React Hooks?

React Hooks should be used in functional components when you need to add state management, perform side effects, access context, or implement custom functionality that involves component lifecycle features without using classes. They are particularly useful for simplifying code, enhancing code reuse with custom hooks, and managing local component state and effects in a more readable and functional-oriented way.

Hooks provide a more direct API to React concepts you already know—state, lifecycle, context, and refs—and make your component logic more modular and easier to understand. Therefore, whenever you’re building function components and need these capabilities, Hooks are the appropriate and recommended approach.

CRS Info Solutions stands out for its exceptional React.js training in Hyderabad, tailored specifically for students. Their program focuses on practical, hands-on learning, ensuring that students not only understand React.js training Bangalore concepts but also apply them effectively in real-world scenarios. This approach has established CRS Info Solutions as a go-to destination for aspiring React.js developers in the region.

The Most Commonly Used Hooks

useState Hook

The State Hook in React, commonly referred to as useState , is one of the basic Hooks provided by React that lets you add state to functional components. Before hooks were introduced, state could only be used in class components.

Here’s an example of how you can use the useState Hook in a functional component to manage a counter:

import React, { useState } from 'react';

function Counter() {
  // Declare a new state variable, which we'll call "count"
  // The useState hook returns an array with two elements:
  // the current state value (count) and a function that lets you update it (setCount)
  const [count, setCount] = useState(0);

  return (
      <h1>Counter: {count}</h1>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(count - 1)}>Decrement</button>
      <button onClick={() => setCount(0)}>Reset</button>

export default Counter;

Here’s a breakdown of the example:

  1. Importing useState: At the beginning, useState is imported from ‘react’.
  2. Declaring state in a functional component: Inside the Counter function component, useState is called to create a new state variable. The initial state is set to 0 .
  3. Reading state: The state variable count is used directly in the JSX to display the current count.
  4. Updating state: setCount is used to update the state. This function is called within the onClick handlers of the buttons:
    • The first button increments the count.
    • The second button decrements the count.
    • The third button resets the count to zero.

useEffect Hook

The Effect Hook, known as useEffect , allows you to perform side effects in functional components. It is similar to lifecycle methods like componentDidMount , componentDidUpdate , and componentWillUnmount in class components. You can use useEffect for various tasks such as fetching data, setting up a subscription, or manually changing the DOM in React components.

Here’s an example demonstrating how to use useEffect to fetch data from an API and display it:

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

function UserData() {
    // State to store user data
    const [user, setUser] = useState(null);
    // State to store loading status
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        // Function to fetch user data
        const fetchUserData = async () => {
            try {
                const response = await fetch('');
                const data = await response.json();
                setUser(data); // Set user data
                setIsLoading(false); // Update loading status
            } catch (error) {
                console.error('Failed to fetch data:', error);
                setIsLoading(false); // Update loading status on error

    }, []); // Empty dependency array means this effect runs only once after the initial render

    if (isLoading) {
        return <div>Loading...</div>;

    return (
            <h1>User Details</h1>
            {user ? (
                    <li>Name: {}</li>
                    <li>Email: {}</li>
            ) : (
                <p>No user data available.</p>

export default UserData;
  1. Importing Hooks: useState and useEffect are imported from React.
  2. State Initialization: Two state variables are initialized:
    • user to store the user data.
    • isLoading to track whether the data is still loading.
  3. Using useEffect:
    • The useEffect Hook is used to perform the side effect of fetching user data.
    • The side effect function fetchUserData is defined and called within useEffect . It fetches user data from an API, updates the state with the data, and sets the loading status.
    • An empty dependency array ( [] ) is passed to useEffect , indicating that the effect should run only once after the initial render, similar to componentDidMount .
  4. Conditional Rendering:
    • If isLoading is true, the component renders a loading message.
    • Once the data is loaded, it checks if user data is available and displays it; otherwise, it shows a message that no data is available.

Advantages of Using Hooks

  1. Simplified Code Structure: Hooks allow you to write cleaner and more readable code by eliminating the need for complex class-based components. They enable you to use state and other React features without writing a class, which can make your components simpler and more straightforward to understand and maintain.
  2. Enhanced Reusability: Hooks promote better code reusability through custom hooks. You can create your own hooks that encapsulate common behaviors or side effects, making these functionalities easily reusable across different components. This reduces code duplication and increases the efficiency of your development process.
  3. Improved Organization of Related Logic: Hooks help in organizing related component logic in a more modular and cohesive way. Instead of having lifecycle methods spread across various parts of a class component, you can group related logic within a single hook. This organization makes it easier to manage and track side effects and state-related logic within components.

Building Custom Hooks

Custom Hooks are a mechanism to reuse stateful logic across multiple components. By extracting component logic into a custom Hook, you can share it across different components.

Example of a Custom Hook:

function useDocumentTitle(title) {
  useEffect(() => {
    document.title = title;

Rules of Hooks

React Hooks, introduced in React 16.8, allow you to use state and other React features without writing a class. Hooks are functions that let you “hook into” React state and lifecycle features from function components. When using Hooks, there are some important rules you must follow to ensure they work correctly and your components behave as expected. Here are the main rules of Hooks:

  1. Only Call Hooks at the Top Level: Do not call Hooks inside loops, conditions, or nested functions. Hooks should always be used at the top level of your React function, before any early returns. This ensures that Hooks are called in the same order each time a component renders, which is necessary for React to correctly preserve the state of Hooks between multiple useState and useEffect calls.
  2. Only Call Hooks from React Functions: You should only call Hooks from React function components or from custom Hooks. This rule ensures that all stateful logic in a component is clearly visible from its source code.
  3. Use the Custom Hooks Naming Convention: Custom Hooks should start with use (e.g., useFetch or useFormInput ). This convention is not enforced by React but is important for making your code more readable and reusable, as well as helping you to automatically enforce the rules of Hooks.

Explanation of the Rules:

  • Consistent Hook Calls for State Preservation: The order in which Hooks are called must be consistent between renders. This is why Hooks can only be called at the top level. If you were to use a Hook inside a loop or conditional, the number of Hook calls could change between renders, leading to bugs and inconsistencies in the component state.
  • Scope of Hook Calls: Hooks leverage React’s internal mechanism to keep track of state and effects across renders. Calling Hooks from regular JavaScript functions or classes would break this mechanism because those functions could be called in a different order or with different frequency than React expects.

Types of React Hooks

React Hooks are functions that allow you to use React features like state and lifecycle methods in functional components. Here’s a brief overview of each type of built-in React Hook:

State Hooks ( useState ): Allow functional components to hold and set state.

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

Context Hooks (useContext): Enable components to subscribe to React Context without a Consumer.

const value = useContext(MyContext);

Ref Hooks (useRef): Provide a way to access DOM nodes or keep mutable variables between renders.

const myRef = useRef(initialValue);

Effect Hooks (useEffect): Used for performing side effects in function components (similar to lifecycle methods in class components).

useEffect(() => { document.title = `You clicked ${count} times`; });

Performance Hooks (useMemo and useCallback): Optimize performance by memorizing complex functions (useMemo) and callbacks (useCallback) to prevent unnecessary re-renders.

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

Resource Hooks (useDeferredValue, useTransition): Manage concurrency in React, helping keep the app responsive by deferring updates (useDeferredValue) or transitioning states at lower priorities (useTransition).

const deferredInput = useDeferredValue(input);

Other Hooks (useImperativeHandle, useLayoutEffect, useDebugValue): Offer more nuanced control over the component lifecycle and debugging, like modifying instance methods of child components (useImperativeHandle) or running synchronous layout effects (useLayoutEffect).

useDebugValue(isOnline ? 'Online' : 'Offline');

Migrating from Class Components to Hooks

Migrating to Hooks from class components can simplify your components and make them more maintainable. However, it’s important to understand that Hooks don’t cover all use cases for classes yet, and there is no need to rewrite existing code if it’s already using classes.

Handling Side Effects

useEffect is the Hook that replaces lifecycle methods like componentDidMount , componentDidUpdate , and componentWillUnmount . It’s crucial to understand how dependencies work in useEffect to control when side effects run.

State and Lifecycle with Hooks

  • useState allows you to add state to functional components.
  • useEffect enables you to perform side effects in your components, such as data fetching, subscriptions, or manually changing the DOM.

Common Pitfalls and Best Practices

  1. Overusing Effects: Use effects sparingly and only for interactions with the outside world like API calls, subscriptions, etc.
  2. Misunderstanding Dependencies: Ensure you correctly specify dependencies in useEffect to avoid unnecessary renders or stale data.
  3. Creating Custom Hooks for Complex Logic: For complex stateful logic, consider creating custom Hooks for better reusability and organization.

Performance Considerations

While Hooks make components cleaner, they can also lead to performance issues if not used carefully. Use the useMemo and useCallback Hooks to optimize performance by memoizing expensive calculations and preventing unnecessary renders.


React Hooks have opened new horizons in the way we write React applications, making functional components as powerful as class components. They provide a more intuitive and functional way to handle state and side effects, leading to cleaner and more maintainable codebases. As you adopt Hooks in your React development, remember that they are not just a feature, but a new mindset, encouraging you to think about your components and their stateful logic in a more modular and reusable way. With Hooks, the functional component has truly become a first-class citizen in the React world.

Enroll for our real time job oriented React js training in Hyderabad, kick start today!

Comments are closed.