0
0
Reactframework~5 mins

Why custom hooks are used in React

Choose your learning style9 modes available
Introduction

Custom hooks help you reuse code easily in React. They keep your components clean and simple by sharing logic.

When you want to share the same logic between multiple components.
When your component code is getting too long or complicated.
When you want to separate concerns for better readability.
When you need to reuse stateful logic without repeating code.
When you want to keep your code organized and easier to test.
Syntax
React
function useCustomHook() {
  // use React hooks here
  return someValue;
}
Custom hooks always start with the word 'use' to follow React rules.
You can use built-in hooks like useState or useEffect inside your custom hook.
Examples
This custom hook manages a counter state and provides a function to increase it.
React
import { useState } from 'react';

function useCounter() {
  const [count, setCount] = useState(0);
  const increment = () => setCount(count + 1);
  return { count, increment };
}
This custom hook tracks the window width and updates it when the window is resized.
React
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;
}
Sample Program

This example shows a custom hook useToggle that manages a boolean state. The component uses it to toggle text between ON and OFF with a button.

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

function useToggle(initialValue = false) {
  const [value, setValue] = useState(initialValue);
  const toggle = () => setValue(!value);
  return [value, toggle];
}

export default function ToggleComponent() {
  const [isOn, toggleIsOn] = useToggle();
  return (
    <>
      <p>The switch is {isOn ? 'ON' : 'OFF'}</p>
      <button onClick={toggleIsOn} aria-pressed={isOn} aria-label="Toggle switch">
        Toggle
      </button>
    </>
  );
}
OutputSuccess
Important Notes

Always name custom hooks starting with 'use' so React knows they follow hook rules.

Custom hooks help keep your components smaller and easier to read.

You can combine multiple hooks inside a custom hook to share complex logic.

Summary

Custom hooks let you reuse stateful logic across components.

They keep your code clean and organized.

Always start their names with 'use' to follow React conventions.