0
0
Reactframework~5 mins

Creating custom hooks in React

Choose your learning style9 modes available
Introduction

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

You want to share stateful logic between multiple components.
You need to organize complex logic into smaller, reusable parts.
You want to keep your components focused on UI, not logic.
You want to avoid repeating the same code in different places.
Syntax
React
function useCustomHookName() {
  // use React hooks like useState, useEffect here
  return someValue;
}

Custom hook names must start with use to follow React rules.

Inside custom hooks, you can use other hooks like useState or useEffect.

Examples
This hook manages a counter state and returns the count and a function to increase it.
React
function useCounter() {
  const [count, setCount] = React.useState(0);
  const increment = () => setCount(count + 1);
  return { count, increment };
}
This hook tracks the window width and updates it when the window resizes.
React
function useWindowWidth() {
  const [width, setWidth] = React.useState(window.innerWidth);
  React.useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  return width;
}
Sample Program

This component uses a custom hook useToggle to manage a boolean state. The button toggles the state between ON and OFF. It also includes accessibility with aria-pressed and aria-label.

React
import React from 'react';

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

export default function ToggleComponent() {
  const [isOn, toggleIsOn] = useToggle();

  return (
    <div>
      <p>The switch is {isOn ? 'ON' : 'OFF'}</p>
      <button onClick={toggleIsOn} aria-pressed={isOn} aria-label="Toggle switch">
        Toggle
      </button>
    </div>
  );
}
OutputSuccess
Important Notes

Always start custom hook names with use so React knows they follow hook rules.

Custom hooks help keep your components clean by moving logic out.

Use accessibility attributes like aria-pressed on interactive elements for better keyboard and screen reader support.

Summary

Custom hooks let you reuse logic across components easily.

Name custom hooks starting with use.

They help keep components focused on UI and improve code organization.