React Hooks tutorials for beginners-13

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.

--

--

--

Founder TWD, JavaScript & ReactJS Trainer, Youtuber, Blogger

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Learn GatsbyJS by creating a tourism site -14

Publishing First npm Package

Restaurant Site Project with GatsbyJS-18

Architect a Blockchain Supply Chain Solution Part B Project FAQ — Udacity Blockchain

[Mal Series #2] Phishing Web Page

Design Patterns with Typescript — Strategy

Angular vs React.js in Enterprise Level Application

How to Work with Your Programming Mentor

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

Founder TWD, JavaScript & ReactJS Trainer, Youtuber, Blogger

More from Medium