DEV Community

Muhammad Bilal
Muhammad Bilal

Posted on

How to create custom hooks in React?

How react custom hooks work?

React custom hooks work like other react hooks, you have to define hooks at the top. I have created one custom hook useScroll

export const FunctionName = () => {
    const { status } = useScroll()
Enter fullscreen mode Exit fullscreen mode

So let's learn further above it. we are going to create a file and we will create the function useScroll in it, Remember for creating custom hooks you need to add use Before the function name. Custom hooks return states, variables, and functions, As you have seen below that useScroll function returns status.

import { useEffect, useState } from 'react'

export const useScroll = () => {
    const [status, setstatus] = useState(false)

    return { status }
}

Enter fullscreen mode Exit fullscreen mode

So we have almost created a hook let's see what it returning. I'm going to call the hook in the Nav component and after distructing useScroll we got status from it, which we are returning from the useScroll component. In the next line, we are going to console the status.
Guess what is the result?

export const Nav = () => {
    const { status } = useScroll()
    console.log(status)
Enter fullscreen mode Exit fullscreen mode

Oh yeah, you got it, it's returning false. Do you know to make status true? let's again move to useScroll function and see what we can do it. I have created a function onStateUpdate in it and updated the status in it and then returned it from useScroll function.

export const useScroll = () => {
    const [status, setstatus] = useState(false)

    const onStateUpdate = () => {
        setstatus(!status)
    }
    return { status, onStateUpdate }
}
Enter fullscreen mode Exit fullscreen mode

We are going to move to the Nav component where we called useScroll hook. and we are going to distruct the onStateUpdate function useScroll hook and going to use it. when we click on the button the state going to change from false to true and true to false.

export const Nav = () => {
    const { status , onStateUpdate } = useScroll()
    console.log(status)`
   return <button onClick={onStateUpdate}>
          Click to change it to :{status}
          </button>
}
Enter fullscreen mode Exit fullscreen mode

Why we need custom hooks?
As we sometime need to perform same code multiple time so to avoid it we create custom hook. it work like normal function in which which we can update state and even can use other hooks in it like useRef , useEffect and others.

Regards

Muhammad Bilal

Top comments (0)