DEV Community

AnkitPat
AnkitPat

Posted on

Write your own custom hook for Favourite count.

So with react latest versions, now you are getting more features like hooks. By which you can achieve things more easily and will less code ofcourse.

In many cases, if we need to have any functionality for our application. There are a-lot of libraries, packages available for doing same things. But if there is no hook or library exist? What do you do?

As a React developer, it's important to learn the process of creating custom hooks to solve problems or add missing features within your own React projects.

In this step-by-step guide, I will show you how to create your own custom React hooks from writing word by word.

Custom hooks:
Custom hooks are just an javascript functions with some variable and functions which we can export to be called from outside and variable to access newest value of changed things.

Step-1 : Create a dummy app as "custom-hooks"

npx create-react-app custom-hooks

After successfully completion of above command to make sure your app is working.

cd custom-hooks

npm start
Enter fullscreen mode Exit fullscreen mode

*Step-2 : Make sure your app is running now on localhost:3000 *

Image description

**Step-3 : Create a file "useFavouriteCount.js" to write our custom hook logic.

Go to the src folder and create file “useFavouriteCount.js” to write the code for custom Hook and write the below code:

import { useState } from 'react';
function useFavouriteCountHook() {
   const [favouriteCount, setFavouriteCount] = useState({ count: 0 });

   const changeFavouriteCount = () => {
      setFavouriteCount({ count: favouriteCount.count + 1 }) 
    }
   return { favouriteCount, changeFavouriteCount };
}
export default useFavouriteCountHook;
Enter fullscreen mode Exit fullscreen mode

Let's decompile the code first:

  • We're importing useState in below line:
import {useState} from 'react';
Enter fullscreen mode Exit fullscreen mode

Created a function/hook with name "useFavouriteCountHook":

function useFavouriteCountHook() {
    ...
}
Enter fullscreen mode Exit fullscreen mode

Using useState we should create a new state with “favouriteCount” and initialize with an object “{ count: 0 }”:

const [favouriteCount, setFavouriteCount] = useState({ count: 0 });
Enter fullscreen mode Exit fullscreen mode

Now, as i said earlier we have to define a variable and a function. Variable we defined using useState, lets define function to update our state values.

 const changeFavouriteCount = () => {
      setFavouriteCount({ count: favouriteCount.count + 1 }) 
    }
Enter fullscreen mode Exit fullscreen mode

Now return variable and functions.

return { favouriteCount, changeFavouriteCount };
Enter fullscreen mode Exit fullscreen mode

As stated earlier, this function should be exposed/exported so other component can import it and use it as hook.

export default useFavouriteCountHook;
Enter fullscreen mode Exit fullscreen mode

Step-4 : Using our custom hook in our code

Open src/app.js, where we have to import custom hook from useFavouriteCountHook file.

Your code should look like these:

import React from 'react';
import useFavouriteCount from './useFavouriteCount';
import './App.css';
function App() {
  const favouriteHook = useFavouriteCount();
  return (
      <div>
        <h1>count:{favouriteHook.favouriteCount.count}</h1>
        <button type='button' onClick=
                {favouriteHook.increaseFavouriteCount}>Increment</button>

          <button type='button' onClick=
                  {favouriteHook.decreaseFavouriteCount}>Decrement</button>
      </div>
  );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

Or you can use it like these as well:

import React from 'react';
import useFavouriteCount from './useFavouriteCount';
import './App.css';
function App() {
  const {favouriteCount, increaseFavouriteCount, decreaseFavouriteCount} = useFavouriteCount();
  return (
      <div>
        <h1>count:{favouriteCount.count}</h1>
        <button type='button' onClick=
                {increaseFavouriteCount}>Increment</button>

          <button type='button' onClick=
                  {decreaseFavouriteCount}>Decrement</button>
      </div>
  );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

*Step-5 : Run the app and see the browser using localhost:3000: *

Demo

You can also find above code on Github Repo

Conclusion:
In this blog, you learned the following things:

  • About custom hook.
  • Created your own hook.
  • Used same hook in component with two different ways.

Thanks for reading.

Top comments (0)