Introduction to React Hooks – A Modern Way to Manage State and Side Effects

Pushkar RoyPushkar Roy
5 min read

In this article, we'll walk through the what, why, and how of React Hooks – including their history, basic syntax, types, and best practices. Let’s go.

🕰️ A Brief History of Hooks

managing state and lifecycle logic in functional components wasn complex way. Developers had to rely on class components to use features like state, componentDidMount, or shouldComponentUpdate.

In 2019, React 16.8 introduced Hooks – enabling state and side-effect management directly inside functional components. This not only reduced performance but also enhanced logical part, reuse and cleaner code.let’s deep dive into Hooks.

📘 What Are React Hooks?

Hooks are powerful features in React that enable functional components to manage state, handle side effects, and enhanced component logic in real-time — all without converting them into class components.

🧾 Basic Syntax of Common Hooks

const [state,setState] = useState(initialState);

✅ Advantages of Using Hooks

State in Functional Components

Hooks empower functional components with their own internal state without needing a class.

Improved Code Reusability

Custom hooks allow you to extract and reuse stateful logic across components.

Better Separation of Concerns

Hooks enable you to group related logic (e.g., fetching, subscribing) into one place, improving readability.

Cleaner & Smaller Components

Hooks promote smaller, composable, and testable components with reduced boilerplate.

🧩 Types of React Hooks

React provides two categories of hooks:

1. Basic (Built-in) Hooks

🔹 1. useStateState Management

const [state, setState] = useState(initialValue);

Used to declare and update state variables in functional components.

🔹 2. useEffectSide Effects (like lifecycle methods)

useEffect(() => {
  // side effect logic
  return () => {
    // cleanup (optional)
  };
}, [dependencies]);

Replaces lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.


🔹 3. useContextAccess Context API

const value = useContext(MyContext);

Allows you to consume values from a React.Context without a <Consumer> wrapper.


🔹 4. useRefMutable Ref and DOM Access

 const inputRef = useRef(initialValue);

Returns a mutable object that persists across renders. Often used to access DOM elements directly.


🔹 5. useReducerComplex State Management

 const [state, dispatch] = useReducer(reducer, initialState);

Alternative to useState for managing complex state logic or multiple related state variables.

🔹 6. useMemoMemoize Expensive Computations

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

Prevents recalculation of expensive values unless dependencies change.


🔹 7. useCallbackMemoize Functions

const memoizedCallback = useCallback(() => {
  doSomething();
}, [dependencies]);

Useful for passing stable function references to optimized child components.


🔹 8. useLayoutEffectSynchronous Version of useEffect

useLayoutEffect(() => {
  // runs before painting the screen
}, []);

Like useEffect but runs synchronously after all DOM mutations.


🔹 9. useImperativeHandleCustom Instance Methods (with forwardRef)

useImperativeHandle(ref, () => ({
  customMethod() { ... }
}));

Customize what’s exposed to parent components via ref.


2. Custom Hooks

Custom Hooks are user-defined functions that start with the word use and allow logic sharing between components.

🔹Custom HooksReusable Logic

function useWindowSize() {
  const [size, setSize] = useState(window.innerWidth);
  // logic here
  return size;
}

Build your own reusable hooks using any of the built-in ones.

Examples of how to use hooks in code

✅ 1. useWindowWidth – A Custom hook to Track Window Width

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;
}

✅ 2. useToggle – Toggle Boolean State

import { useState } from 'react';
function useToggle(initialValue = false) {
  const [state, setState] = useState(initialValue);
  const toggle = () => setState(prev => !prev);

  return [state, toggle];
}

// const [isVisible, toggleVisibility] = useToggle();

✅ 3. useFetch – Basic Data Fetching Hook

import { useState, useEffect } from 'react';

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let isMounted = true;

    fetch(url)
      .then(res => res.json())
      .then(data => {
        if (isMounted) {
          setData(data);
          setLoading(false);
        }
      });

    return () => { isMounted = false };
  }, [url]);

  return { data, loading };
}

// const { data, loading } = useFetch('https://api.example.com/data');

📏 Rules of Hooks

Some fundamental rules when using Hooks:

  1. Only Call Hooks at the Top Level,Don’t call Hooks inside loops, conditions, or nested functions.

  2. Only Call Hooks from React Functions,Call them from functional components or custom hooks only.

📌 Ending

"In this article, we explored the foundational concepts of React Hooks. But there's more! Stay tuned for the next part where we'll dive deeper into advanced hooks and real-world patterns." Thank You. .

2
Subscribe to my newsletter

Read articles from Pushkar Roy directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Pushkar Roy
Pushkar Roy

Hey 👋 I am Pushkar , I am learning person holding skills in Developing UI as well as backend using NodeJS and a passionate programmer who loves to code. I am creatively curious and a self-learner and self-motivated person who believes in smart work achieved from hard work . 🚀 Currently, my focus is on Full Stack Development, where I engage in daily practice of Data Structures and Algorithms and exploring web3 and new technologies. I’m also active in Open Source and looking forward to contributing to Open-Source Projects. ✨Proficient in Data Structures and Algorithms with a strong command of C++. 💻Front-end development expertise using ReactJS and NextJS with MySQL, ExpressJs ensuring the creation of fully responsive and scalable websites. 🌐Currently, I am focusing on JavaScript, TypeScript, NodeJS, React, NextJs and Data Structure. Let's connect if you share the love for coding, learning, and building cool things! 🤝