react js-tutorial

React Custom Hooks

You can use many of the built-in hooks that React.Js offers in your React apps. In addition to them, you can create your own unique hooks and use them in your apps for improved readability and less code. Normal JavaScript methods with the prefix “use” make up custom hooks, which may invoke other hooks (built-in or custom).

The major reason you should use custom hooks in your React applications is to uphold the DRY (Don’t Repeat Yourself) principle. Consider the situation when you need to employ some logic that uses some built-in hooks in various functional components. You may either write the same logic in each component individually (which goes against the DRY principle), or you can construct a new function, encapsulate the logic inside of it, and call it from the other components. Since you only need to write the reasoning once, the second alternative is unquestionably the preferable option. The unique hook in this case is the independent function you defined. In order to apply your logic in different functional components (hooks are ineffective in class components), simply construct a separate custom hook and use it.

Building a custom hook

Building a custom hook is equivalent to writing a JavaScript function with the word “use” at the beginning of its name. It can take any kind of parameters, use other hooks inside it, and return anything you want. In the example below, the custom hook “useCustomHook” uses the state variable “counter.” Every time the value of the counter updates, the function supplied to the useEffect hook is called. The method “resetCounter” increments the value of the counter by 1. The method runs some code that will be utilised in numerous components (the code has been deleted to concentrate on using custom hooks rather than implementing a logic). The “resetCounter” function is what this particular hook returns.

Filename- src/useCustomHook.js:

import {useState , useEffect} from "react";
  
// Remember to start the name of your custom hook with "use"
function useCustomHook(initializer , componentName){
    const [counter , setCounter] = useState(initializer);
      
    // Increases the value of counter by 1
       function resetCounter(){
        setCounter(counter + 1);
    }
      
    useEffect(() => {
        // Some logic that will be used in multiple components
        console.log("The button of the " 
        + componentName + " is clicked "
        + counter + " times.");
    } , [counter , componentName]); 
      
    // Calls the useEffect hook if the counter updates
    return resetCounter;
}
  
export default useCustomHook;

Using the custom hook in components: To use the custom hook in your components just import the “useCustomHook” function from “useCustomHook.js” file in the “src” folder.

Filename- src/components/FirstComponent.js:

import React from "react";
  
// importing the custom hook
import useCustomHook from "../useCustomHook";
  
function FirstComponent(props){
  
    // ClickedButton = resetCounter;
    const clickedButton = useCustomHook(0 , "FirstComponent"); 
      
    return (
        <div>
            <h1> This is the First Component</h1>
            <button onClick={clickedButton}> 
                  Click here!
            </button>
        </div>
    );
}
  
export default FirstComponent;

Filename : src/components/SecondComponent.js:

import React from "react";
  
// Importing the custom hook
import useCustomHook from "../useCustomHook";
  
function SecondComponent(props){
  
    // ClickedButton = resetCounter;
    const clickedButton = useCustomHook(0 , "SecondComponent"); 
      
    return (
        <div>
            <h1> This is the Second Component</h1>
            <button onClick={clickedButton}> 
               Click here!
            </button>
        </div>
    );
}
  
export default SecondComponent;

Filename: src/App.js:

import React from 'react';
import './App.css';
import FirstComponent from './components/FirstComponent';
import SecondComponent from './components/SecondComponent';
  
function App(){ 
    return( 
        <div className='App'> 
        <FirstComponent />
        <SecondComponent />
        </div> 
    );
} 
    
export default App;

Even when we declare the dependency array, the useEfffect is called after the initial render. This means that after the initial render and whenever the variables in the dependency array are modified, the callback function supplied to the useEffect hook is run. This first execution cannot be stopped in a straightforward manner. Now, if you click the first button (the FirstComponent’s button) and look at the console, you will notice that the counter’s value rises by 1 with each click, and the new number is displayed on the console.

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published.