DEV Community

Himanshupal0001
Himanshupal0001

Posted on

Why React Developers write Custom Hooks?

Being a React developer it's a common practice to use hooks. React provides many hooks out of the box like useState, useEffect,useContext etc for common use cases. However, most real-world applications require logic that goes beyond these basic hooks. This is where custom hooks come in handy.

I am sure you'll encountered such situations where you need to write customs hooks to achieve desired functionality.

But have you ever wondered-

  • Why do we write custom hooks instead of writing normal functions?
  • What is the difference between normal function and custom hooks?

Many developers get a hard time understand the difference between both. Even finding answers online couldn't give the satisfactory answers but just the copy paste definition of react hooks you find on React official website.

It is important to know the actual reason why to write a hook before even how to write a hook!!

Before discussing main topic let's do some homework , shall we 🤓!!

Let me just copy paste what is custom hook, what is normal react hook and rules to define both react hook and custom hook.

What is React Hook?

React hooks are predefined JavaScript functions powered by React to do certain tasks. It will hook into a react state lifecycle and keep track of it. For example a useState hook bind to its variable which keep track that if anything changes for that variable it will trigger a re-render on its own.

What are the rules for React hooks?

  • Hooks can only be called inside React function components.
  • Hooks can only be called at the top level of a component.
  • Hooks cannot be conditional or cannot be called in conditional block.

What are custom hooks?

Customs hooks are user defined hooks that are JavaScript functions supercharged ⚡by React. You can use React predefined hooks, define functions ,states and variables.

Rules for custom hooks

  • Your custom hook should start with the keyword use, for example, useAuthState, useFetch, etc.
  • Must follow React hooks rule.
  • Must be a funtion.

These are the things you must've known about hooks in general and custom hooks and you already read about custom hooks are reusable, abstract etc etc.

Now let's get down to business, Why just why custom hooks!!

See the below code , one is normal function and other is custom hook.

** Normal js function **

import { useDispatch } from 'react-redux'
import { signOut } from 'firebase/auth'
import { auth } from '../utils/firebase';
import { removeUser } from '../redux/authSlice'
import { useNavigate } from 'react-router-dom';

export const handleSignout = (token) => {
    const disptach = useDispatch();
    const navigate = useNavigate();
    try {
        if (token) {
            signOut(auth)
                .then(() => {
                    disptach(removeUser());
                    navigate('/')
                })
                .catch(err => {
                    console.log(err)
                })
        }

    }
    catch (err) {
        console.log(err)
    }
}
Enter fullscreen mode Exit fullscreen mode

** Custom hook **

import { useDispatch } from 'react-redux'
import { signOut } from 'firebase/auth'
import { auth } from '../utils/firebase';
import { removeUser } from '../redux/authSlice'
import { useNavigate } from 'react-router-dom';

const useSignout = () => {
    const disptach = useDispatch();
    const navigate = useNavigate();

    const handleSignout = (token) => {
        if (token) {
            signOut(auth)
                .then(() => {
                    disptach(removeUser());
                    navigate('/')
                })
                .catch(err => {
                    console.log(err)
                })
        }
    }

    return handleSignout;
}

export default useSignout;
Enter fullscreen mode Exit fullscreen mode

If you observed carefully you see there's only minor difference but logic is exactly the same. But one will give error and other is not. Why is this?

*The answer is stateful functions. *

Yeah ....

Image description

But what is stateful functions ?
Image description
** Stateful ** functions are js functions that use reacts usestate to manage state on component level.

Why we write customs hooks?

We write custom hooks to leverage the power of react. A custom hook it that function which can use react built in hooks, respect the react hook rules and custom hook rules and able to manage states within own scope.

For example

Below is the logout button page and a normal javascript function is bind with it.

The function is same , which mentioned above.

logout button page

ON click this will throw an error that complaining about rules have not been followed. See below

err

** Now see the below with sign-out hook **

usesignout

This logout button is bind with useSignout() hook. It didn't returned any error and worked as expected.

Conclusion

If you still struggling to understand what are custom hooks just remember that the functions in which you use react predefined hooks and that function must follow the hook rules are customs hooks which used to change state or do sideEffects.

Top comments (0)