0
0
Reactframework~5 mins

Hook naming conventions in React

Choose your learning style9 modes available
Introduction

Hooks need clear names so you and others understand what they do. Good names help keep code easy to read and fix.

When creating a new custom hook to reuse logic in multiple components.
When using built-in React hooks like useState or useEffect in your components.
When sharing hooks with teammates or in open source projects.
When debugging or reading code to quickly know what a hook does.
Syntax
React
function useCustomHookName() {
  // hook logic here
}

Hook names must start with use to let React know it is a hook.

Use camelCase after use, like useFetchData or useToggle.

Examples
A custom hook named useCounter that manages a count state.
React
function useCounter() {
  const [count, setCount] = React.useState(0);
  const increment = () => setCount(count + 1);
  return { count, increment };
}
A custom hook named useWindowWidth that tracks the window width.
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 example shows a custom hook useToggle that manages a boolean state. The component ToggleComponent uses it to switch between ON and OFF states when the button is clicked.

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 (
    <>
      <button onClick={toggleIsOn} aria-pressed={isOn} aria-label="Toggle button">
        {isOn ? 'ON' : 'OFF'}
      </button>
    </>
  );
}
OutputSuccess
Important Notes

Always start hook names with use so React can check rules of hooks.

Keep hook names descriptive but short to explain what they do.

Do not call hooks conditionally or inside loops to avoid bugs.

Summary

Hook names must start with use.

Use camelCase after use for readability.

Good names help understand and reuse hook logic easily.