How to create your own React Custom hooks (example)
In this tutorial, you are going to learn about how to create your own react custom hooks with the help of examples.
First, we will see an example of a counter using useState
hook.
import React, { useState } from "react";
function App() {
const [count, setCount] = useState(0);
function Increment() {
setCount(count + 1);
}
function Decrement() {
setCount(count - 1);
}
return (
<div className="App">
<h1>{count}</h1>
<button onClick={Increment}>Increment</button> <button onClick={Decrement}>Decrement</button> </div>
);
}
In the above example, we created a counter which is increments
by 1 when we click on a increment
button and decrements by 1
when we click on a decrement
button.
Suppose we need this counter in different places of our app in such cases we can build our custom react hook instead of creating same counter logic again and again.
Custom hooks
Custom hooks are JavaScript functions, whose name starts with use
and they can call other
react hooks.
Now, we are removing the counter
logic from the above example and creating our own custom hook called useCounter
.
import { useState } from "react";
function useCounter(val, step) {
const [count, setCount] = useState(val);
function Increment() {
setCount(count + step); }
function Decrement() {
setCount(count - step); }
return [count, Increment, Decrement];}
export default useCounter;
In the above code, we created our own custom hook called useCounter
with two parameters val
and step
and returning an array with count
value , Increment
and Decrement
functions.
-
val: Initial value of the counter.
-
step: How many steps counter needs to increment or decrement.
Using the Custom hook
Let’s use the useCounter
custom hook inside App
component by importing it from the counter-hook.js
file.
import React from "react";
import useCounter from "./counter-hook";
function App() {
const [count, Increment, Decrement] = useCounter(0, 1);
return (
<div className="App">
<h1>{count}</h1>
<button onClick={Increment}>Increment</button>
<button onClick={Decrement}>Decrement</button>
</div>
);
}
export default App;
Now, we have a reusable counter logic we can use it whenever we need a counter in our react app.