MT / Portfolio

Crafted with precision

00%

Status

Initializing

All articlesreact

Modern React Hooks: A Complete Guide to Building Scalable React Applications

By Md Moniruzzaman Tonoy · · 12 min read

Modern React Hooks: A Complete Guide to Building Scalable React Applications

Introduction to React Hooks

React Hooks changed the way developers build modern React applications. Introduced in React 16.8, Hooks allow functional components to use state, manage side effects, access context, and reuse application logic without writing class components.

Today, understanding React Hooks is an essential skill for frontend developers. Whether you are building a small application or a large-scale production platform, Hooks help you organize code, improve maintainability, and create reusable components.

1. Understanding useState

The useState Hook allows functional components to store and update local state. Whenever the state changes, React schedules a re-render so the interface can reflect the latest data.

import { useState } from "react";

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

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(prev => prev + 1)}>
        Increase
      </button>
    </div>
  );
}

export default Counter;

In this example, count stores the current value, while setCount updates it. Functional updates are especially useful when the next state depends on the previous state.

2. Managing Side Effects with useEffect

The useEffect Hook is used to synchronize a component with external systems, such as APIs, browser events, subscriptions, and timers.

import { useEffect, useState } from "react";

function Users() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    const controller = new AbortController();

    async function fetchUsers() {
      try {
        const response = await fetch(
          "https://jsonplaceholder.typicode.com/users",
          { signal: controller.signal }
        );

        if (!response.ok) {
          throw new Error("Failed to fetch users");
        }

        const data = await response.json();
        setUsers(data);
      } catch (error) {
        if (error.name !== "AbortError") {
          console.error(error);
        }
      }
    }

    fetchUsers();

    return () => controller.abort();
  }, []);

  return <div>{users.length} users loaded</div>;
}

The dependency array determines when the effect should re-run. Cleanup functions help prevent outdated subscriptions and unnecessary ongoing work.

3. Sharing Data with useContext

React Context provides a way to share data across components without passing props through every intermediate component. It is useful for authentication information, themes, and application-wide preferences.

import { createContext, useContext } from "react";

const ThemeContext = createContext("light");

function ThemeButton() {
  const theme = useContext(ThemeContext);

  return <button className={theme}>
    Current Theme: {theme}
  </button>;
}

4. Managing Complex State with useReducer

When state transitions become complex, useReducer provides a structured approach. It is useful for forms, multi-step workflows, and state involving multiple related values.

import { useReducer } from "react";

function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    default:
      return state;
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, {
    count: 0
  });

  return (
    <div>
      <p>{state.count}</p>
      <button onClick={() => dispatch({ type: "increment" })}>
        Increase
      </button>
    </div>
  );
}

5. Optimizing Performance

React provides tools such as useMemo, useCallback, and memo to help reduce unnecessary calculations and rendering in suitable situations.

  • useMemo: Caches the result of a calculation between renders.
  • useCallback: Caches a function definition between renders.
  • memo: Can skip rendering a component when its props have not changed.

Do not optimize every component automatically. Measure performance first and apply memoization where it provides a meaningful benefit.

6. Building Custom Hooks

Custom Hooks allow developers to extract reusable stateful logic into independent functions. Their names must start with use.

import { useState, useEffect } from "react";

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

  useEffect(() => {
    const updateWidth = () => {
      setWidth(window.innerWidth);
    };

    window.addEventListener("resize", updateWidth);

    return () => {
      window.removeEventListener("resize", updateWidth);
    };
  }, []);

  return width;
}

7. Common React Hooks Mistakes

  • Calling Hooks conditionally or inside loops.
  • Ignoring dependencies in useEffect.
  • Updating state directly instead of using its setter.
  • Using effects for calculations that can happen during rendering.
  • Adding unnecessary memoization.

Conclusion

React Hooks are fundamental to modern React development. Start with useState and useEffect, then explore Context, Reducer, and custom Hooks. Practice by building real applications, managing API data, creating reusable components, and optimizing actual performance bottlenecks.

Consistent practice and a clear understanding of React's rendering model will help you become a more confident React developer.

#React#React Hooks#useState#useEffect#Frontend#JavaScript