0
0
Reactframework~5 mins

Custom hook best practices in React

Choose your learning style9 modes available
Introduction

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

You want to share stateful logic between multiple components.
You need to separate complex logic from UI code for clarity.
You want to keep your components small and focused.
You want to reuse effects or event handlers in different places.
You want to improve testing by isolating logic.
Syntax
React
import { useState } from 'react';

function useCustomHook() {
  // use React hooks here
  const [state, setState] = useState(initialValue);
  // add logic
  return { state, setState };
}

Custom hooks always start with use to follow React rules.

They can call other hooks inside them.

Examples
A simple counter hook that manages a number and provides a way to increase it.
React
import { useState } from 'react';

function useCounter() {
  const [count, setCount] = useState(0);
  const increment = () => setCount(c => c + 1);
  return { count, increment };
}
This hook tracks the window width and updates when the window resizes.
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 component uses a custom hook useToggle to manage a boolean state. The button toggles the state and updates the text.

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

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

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

  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 prefix custom hooks with use to follow React rules and enable linting.

Keep hooks focused on one task for easier reuse and testing.

Use descriptive names to make your hooks easy to understand.

Summary

Custom hooks let you reuse React logic cleanly.

Start hook names with use and keep them focused.

Use them to separate logic from UI and share code between components.