React JS Rreact Hooks Custom Hooks

Custom hook is basically a javascript function which name starts with 'use'. A custom hook can also call other Hookes if required.

Why required custom hooks?

It is for share logic between components. Its an alternative to HOCs and Render Props.

We can get more idea by looking below example.

1. useCounter.js

useCounter
import { useState } from 'react'; function useCounter() { const [count, setCount] = useState(0); const increment = () => { setCount(prevCount => prevCount + 1) } const decrement = () => { setCount(prevCount => prevCount - 1) } const reset = () => { setCount(0) } return [count, increment, decrement, reset]; } export default useCounter;

1. CounterOne.js

CounterOne
import { useState } from 'react'; import useCounter from './useCounter'; function CounterOne() { const [count, setCount, increment, decrement, reset] = useState(0); return ( <div> <h2> Count {count} </h2> <button onClick={increment}>Increment</button> <button onClick={dncrement}>Decrement</button> <button onClick={reset}>Reset</button> </div> ); } export default CounterOne;

In above code, we have create a useCounter which is almost as same as javascript function and use this customHooks in CounterOne components. When we click on increment button then it will add one count in current count. for decrement button click it will reduce one count in current count and in reset it will reset current count to 0. In this way we can create custom hooks.

 

← Previous