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()
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 }
}
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)
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 }
}
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>
}
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)