Custom Hook in React JS

custom-hook-in-react-js

A custom Hook is a javascript function whose name starts with “use” and that may call other hooks.

Why we create Custom Hooks:

Building your own hooks lets you extract component logic into reusable functions. You can write custom Hooks that cover a wide range of use cases like form handling, animation, declarative subscriptions, timers, and many more.

Create Custom Hooks Syntax:

Use Custom Hook Syntax:

Let’s try to understand with an example. First, we will create a new file named “custom.js“. In “custom.js” we will write our own custom hook logic and export it.

Second, we will create another file named “index.js”. Here we will import our custom hook and use the functionality of custom hook in this file like custom hook returned value and functions or logics.

custom.js file

Create “custom.js” file and copy and paste below code

index.js file

Create “index.js” file and copy and paste below code

As you can see, in custom.js file we return object value, not an array value. That’s why in index.js file we are calling const data= useCustomHook() under Employee function component and rendering the value as {data.salary} and {data.incrementSalary}.

What do we need to make changes if we will return array value instead of object value in custom.js file?

if we will return array value from custom.js then we need to make changes like the below code.

Changes in custom.js file

Changes in index.js file

Learn More: Hooks in ReactJS

Learn More: Effect Hooks in ReactJS

Related posts