0
0
Reactframework~5 mins

Reusing logic with hooks in React

Choose your learning style9 modes available
Introduction

Hooks let you share code between components easily. They keep your code clean and avoid repeating the same logic.

You want to share a timer or counter logic across multiple components.
You need to fetch data in different parts of your app using the same method.
You want to handle form input changes in many forms without copying code.
You want to keep your components simple by moving complex logic out.
You want to reuse animation or scroll tracking logic in several places.
Syntax
React
function useCustomHook() {
  // use React hooks like useState, useEffect here
  return someValue;
}

function Component() {
  const value = useCustomHook();
  return <div>{value}</div>;
}

Custom hooks always start with use to follow React rules.

They can use other hooks inside and return any data or functions.

Examples
This hook shares a counter logic that components can use to count clicks.
React
function useCounter() {
  const [count, setCount] = React.useState(0);
  const increment = () => setCount(c => c + 1);
  return { count, increment };
}

function Counter() {
  const { count, increment } = useCounter();
  return <button onClick={increment}>Count: {count}</button>;
}
This hook tracks the window width and updates 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;
}

function ShowWidth() {
  const width = useWindowWidth();
  return <div>Window width: {width}px</div>;
}
Sample Program

This example shows a custom hook useToggle that manages on/off state. The ToggleButton component uses it to switch text and ARIA attributes for accessibility.

React
import React from 'react';

function useToggle(initialValue = false) {
  const [on, setOn] = React.useState(initialValue);
  const toggle = () => setOn(o => !o);
  return { on, toggle };
}

export default function ToggleButton() {
  const { on, toggle } = useToggle();
  return (
    <button onClick={toggle} aria-pressed={on} aria-label="Toggle button">
      {on ? 'ON' : 'OFF'}
    </button>
  );
}
OutputSuccess
Important Notes

Custom hooks help keep components small and focused on UI.

Always name hooks starting with use so React knows to follow hook rules.

Hooks can return any data type: values, objects, or functions.

Summary

Hooks let you reuse logic without repeating code.

Custom hooks start with use and can use other hooks inside.

Use them to keep your components clean and share behavior easily.