React Hooks tutorials for beginners-13

Nabendu Biswas
3 min readNov 16, 2020

--

React

Welcome to part-13 of the series. You can find part-12 here. We will learn to make custom hooks in this part.

Custom hook

With custom hooks we can add our own functionalities to hooks.

  • A custom hook is basically a JavaScript function whose name starts with “use”.
  • A custom hook can also call other Hooks if required.
  • Custom hooks can be used to share logic like HOCs and Render props.

So, go ahead and create new React project custom-hook by the below command

npx create-react-app custom-hook

After that create a components folder and a file DocTitleOne.js inside it. The content of the file is a simple count state variable, which is increased on the click of a button. We are also updating the title of the page with count using useEffect.

DocTitleOne.js

Suppose, we want similar functionality again. So, we will create another file DocTitleTwo.js inside the components folder, with same content.

DocTitleTwo.js

Now, we will include both Components in App.js

App.js

Now, both buttons can be used to update the title.

Title update

Now, as we are repeating the code, we will avoid it by using custom hooks. We will extract the logic to update the document title in that custom hook. Create a new file useDocumentTitle.js in a new hooks folder. We will move the useEffect logic in it.

useDocumentTitle.js

Now, back in DocTitleOne.js we will use the useDocumentTitle instead of useEffect logic.

DocTitleOne.js

In DocTitleTwo.js we will use the useDocumentTitle instead of useEffect logic.

DocTitleTwo.js

Now, back to localhost we still have the same functionality.

Same Function

This completes part-13 of the series. You can find part-14 here.

You can find the code for the same in this github repo.

--

--

Nabendu Biswas
Nabendu Biswas

Written by Nabendu Biswas

Architect, ReactJS & Ecosystem Expert, Youtuber, Blogger

No responses yet