Custom hook is a function which should be called from the React code & not from the regular JS functions Custom hook function name should start from "use" Custom hook can call other hooks, but normal functions can not Without custom hook Let's make a simple counter component as we normally do.
import { useState } from 'react'
function WithoutCustomHook() {
const [count, setCount] = useState(0)
const increment = () => setCount(count + 1)
const decrement = () => setCount(count - 1)
const reset = () => setCount(0)
return (
<div>
<div>Count: <b>{count}</b></div>
<button onClick={increment}>Increment</button> 
<button onClick={decrement}>Decrement</button> 
<button onClick={reset}>Reset</button>
</div>
)
}
With custom hook Let's extract logic into a custom hook and use it inside a component.
// custom hook
function useCounter(initVal = 0, step = 1) {
const [count, setCount] = useState(initVal)
const increment = () => setCount(count + step)
const decrement = () => setCount(count - step)
const reset = () => setCount(initVal)
return [count, increment, decrement, reset]
}
Now the logic is not encapsulated inside the component, but can live in a separate file and can be utilized by multiple components.
function WithCustomHook() {
const step = 5
const startFrom = 10
const [count, increment, decrement, reset] = useCounter(startFrom, step)
return (
<div>
<div>Count: <b>{count}</b></div>
<button onClick={increment}>Increment by {step}</button> 
<button onClick={decrement}>Decrement by {step}</button> 
<button onClick={reset}>Reset</button>
</div>
)
}
Note, we enhanced the hook by bringing initVal & step arguments.