How react knows that a function is a custom hook
React doesn't explicitly "know" that a specific function is a custom hook. Instead, it relies on naming conventions and the rules of hooks to correctly handle custom hooks.
Naming Convention
Custom hooks in React are simply JavaScript functions that:
- Use other hooks inside them.
- Follow a naming convention that starts with the word
use
.
For example:
function useCustomHook() {
const [state, setState] = useState(0);
// ... more logic using hooks
return [state, setState];
}
Rules of Hooks
React follows specific rules to correctly manage hooks:
- Only Call Hooks at the Top Level: Hooks should only be called at the top level of a function component or a custom hook. They should not be called inside loops, conditions, or nested functions.
- Only Call Hooks from React Functions: Hooks should only be called from function components or custom hooks.
How React Tracks Hooks
React uses an internal mechanism to track the order and number of hooks called during the render process. This is how it maintains the state and effects correctly across re-renders.
When React renders a component:
- It starts rendering from the top of the component.
- As it encounters hooks (
useState
,useEffect
, etc.), it keeps track of the order in which they are called. - If a custom hook is called (e.g.,
useCustomHook
), React treats it like any other function that calls hooks in a specific order. - During subsequent renders, React expects hooks to be called in the same order. This consistency allows React to preserve the state between renders.
Example of Custom Hook Usage
import React, { useState, useEffect } from 'react';
function useCustomHook(initialValue) {
const [value, setValue] = useState(initialValue);
useEffect(() => {
console.log('Value has changed:', value);
}, [value]);
return [value, setValue];
}
function App() {
const [count, setCount] = useCustomHook(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default App;
In this example:
useCustomHook
is a custom hook because it follows the naming convention (use...
) and uses React hooks (useState
anduseEffect
) inside it.- React doesn't explicitly identify
useCustomHook
as a custom hook but treats it like any other function that invokes hooks, preserving the order of hook calls.
Key Points
- Naming Convention: Custom hooks should start with
use
. This is a convention and a way to ensure that hooks are easily recognizable and follow React's rules of hooks. - Consistency: Hooks must be called in the same order on every render to ensure React can correctly track their state and effects.
- React's Internal Mechanism: React keeps track of hooks based on their call order during the render process, which allows it to manage the hooks' state correctly across re-renders.
Published on: Jul 05, 2024, 05:39 AM