How to create and use React custom hooks?

In this blog we will see how to create a custom hook and use it in your React.js application with the help of an example. To use as an example we are going to create a counter. The counter increments by 1 whenever we click on the increment button and decrements by 1 when we click the decrement button. We can build our custom hook in case we need to use this counter in different places in our app.

App.js 
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 the counter uses useState hook. Similarly Custom hooks use JavaScript functions and those functions will always start with use and these functions can call other react hooks. We will remove counter logic from our example and create a custom hook called useCounter. 

Counter-hook.js
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;

Here we have two parameters: val and step. This will return an array with count value, Increment and Decrement functions. Val is the initial value of the counter. Step represents how many steps the counter needs to increment or decrement. We can use the custom hook by importing it from the counter-hook.js file.

App.js


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