React Hooks tutorials for beginners-13

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.

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

Now, we will include both Components in App.js

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

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.

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

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

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

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nabendu Biswas

Nabendu Biswas

589 Followers

Founder TWD, JavaScript & ReactJS Trainer, Youtuber, Blogger