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

Authentication with React, Apollo Client and GraphQL

Publishing First npm Package

Creating Chat Application using Express and Websockets…

How to Use Google Cloud Firestore With Glitch

How to import ESLint issues into SonarQube overview analysis in a frontend application

Beginner’s guide to encoding, encryption and hashing

Vue & Typescript: Handling Types for Injected Properties

JavaScript Date Object Set Methods

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

3 React Hooks You Should Not Miss in 2022

How to make a table in React with Hooks

How to Build a Basic CRUD App with NextJS, React, Redux, Observable and MUI5 Components

State Management and React