Tuesday, March 8, 2022

How to Create Custom hooks in React.js? Example Tutorial

Introduction

The introduction of React hooks in React version 16.8 changed the React development completely. The web application development using React was mostly limited to class components because the state and lifecycle methods were not supported in the functional components. But with React hooks, the state can be used in functional components. Moreover, lifecycle methods like functionality can also be achieved using the useEffect hook. 


React provides extremely useful hooks such as useState and useEffect. Other libraries such as redux also provide useful hooks such as useDispatch and useSelector. Similarly, there are many other popular and not-so-popular React hooks available. But a React developer is not limited to the hooks offered by react and other libraries. We can also create our custom hooks. 



What is a custom hook?

React hooks, basically, are JavaScript functions. So the React hooks are special pre-defined functions. On another hand, custom hooks are manually created functions that help a developer with code reusability. 


In React, the developers rely on “render props” or Higher-order components for code reusability. No doubt these methods are very useful but custom hooks provide code reusability more simply and cleanly. 


So custom hooks are functions that begin with “use” and share the same stateful logic that could be used in multiple components. 


Creating a simple custom hook

Let’s understand how to create and use a custom hook in React with help of a simple example. 


Observe the following “App.js” file. 


const App = () => {

  return (

    <div>

      <button>Increment by 5</button>

    </div>

  );

};

 

export default App;


The above component contains a single button that increments the value by 5. Now, to create a counter for this button, we can simply use the useState hook and write the logic for it in this component only. But suppose, we have another component like the following. 


const Counter2 = () => {

  return (

    <div>

      <button>Increment by 10</button>

    </div>

  );

};

 

export default Counter2;


The “Counter2” component also has a button that increments the value by 10. For this, we can also write the counter logic here only that will be very similar to the earlier one. 


Now, suppose we have another component like the following. 


const Counter3 = () => {

  return (

    <div>

      <button>Decrement by 20</button>

    </div>

  );

};

 

export default Counter3;


Again, the component has a button, but it decrements the value by 20. The counter logic will be similar to the logic we created earlier, but with a little difference. 


The normal approach is to write the same logic in every component. But it is inefficient and not recommended because the almost similar code is being repeated three times. So for code reusability, let’s create a hook named “useCounter”. 


const useCounter = (difference, mode) => {

  const [count, setCount] = useState(0);

};

 

export default useCounter;


First, the basic rule is using the “use” for the hook. The custom will receive to arguments - mode and difference. 


The “mode” can have two values - “INCREMENT” and “DECREMENT” - to determine if increment or decrement is to be done. The second argument, “difference” will hold a number that will determine the value that is going to be added or subtracted. 

Then, the useState hook is used to define a state variable and the function to change it. 


Remember, the custom hook will return an object. In our case, the useCounter hook will return an object containing two values - the state variable and the function to change it. As of now, we have the state variable, i.e. “count”. Let’s create a function.


const changeCount = () => {

  if (mode === "INCREMENT") {

    setCount(count + difference);

  } else if (mode === "DECREMENT") {

    setCount(count - difference);

  }

};


The “changeCount” method will first check the “mode” and according to it, “difference” will be added or subtracted from the “count”. 


How to Create Custom hooks in React.js? Example Tutorial


In the end, “count” and “changeCount” will be returned from the useCounter hook. 


import { useState } from "react";

 

const useCounter = (initialValue, difference, mode) => {

  const [count, setCount] = useState(initialValue);

 

  const changeCount = () => {

    if (mode === "INCREMENT") {

      setCount(count + difference);

    } else if (mode === "DECREMENT") {

      setCount(count - difference);

    }

  };

  return { count, changeCount };

};

 

export default useCounter;


Now, we can use the useCounter hook in the components. Let’s start with the “App” component. 


import "./App.css";

import useCounter from "./useCounter";

 

const App = () => {

  const { count, changeCount } = useCounter(5, "INCREMENT");

 

  return (

    <div className="App">

      <button onClick={changeCount}>Increment by 5</button>

      <h3>{count}</h3>

    </div>

  );

};

 

export default App;


Similarly, use the useCounter hook in the “Counter2”.


import React from "react";

import useCounter from "./useCounter";

 

const Counter2 = () => {

  const { count, changeCount } = useCounter(10, "INCREMENT");

  return (

    <div>

      <button onClick={changeCount}>>Increment by 10</button>

      <h3>{count}</h3>

    </div>

  );

};

 

export default Counter2;

 


And in “Counter3”


import React from "react";

import useCounter from "./useCounter";

const Counter3 = () => {

  const { count, changeCount } = useCounter(20, "DECREMENT");

  return (

    <div>

      <button onClick={changeCount}>Decrement by 20</button>

      <h3>{count}</h3>

    </div>

  );

};

 

export default Counter3;



So, every component is using the same stateful logic in the useCounter hook, thus avoiding writing the same logic again and again. 


Wrapping it up

The custom hooks are very useful if you want to reuse and share stateful logic. Moreover, it is easy to create a custom hook as it is nothing but a JavaScript function. In this article, we discussed what are custom hooks in React.


Other React.js  Articles and Tutorials you may like

Thanks for reading this article so far. If you like this React tutorial about custom hooks then s, please share it with your friends and colleagues. IF you have any questions or feedback, then please ask in the comments. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.