React Hooks tutorials for beginners-13

Image for post
Image for post
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.

Image for post
Image for post
DocTitleOne.js

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

Image for post
Image for post
DocTitleTwo.js

Now, we will include both Components in App.js

Image for post
Image for post
App.js

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

Image for post
Image for post
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.

Image for post
Image for post
useDocumentTitle.js

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

Image for post
Image for post
DocTitleOne.js

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

Image for post
Image for post
DocTitleTwo.js

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

Image for post
Image for post
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.

Written by

UI Lead- ReactJS, JavaScript and everything in-between.

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