Hooks in React

React is a library for building a user interface, that allows users to interact with a website from individual pieces called components written in TypeScript or JavaScript. React is an open-source free library basically for the frontend.
Hooks in React allow a function component to access data and other React features. This can be written in JavaScript or TypeScript depending on user choice. There are predefined hooks by React which are available to manage state and custom React hooks can be built through the combination of these hooks, such as useEffect, useState, useContext, useMemo, and others.

We will discuss some of the various hooks in the React library.

  1. useState: This is one of the most hooks in the React library, it is used to manage state, and update state directly at a particular period.

    For example:

     import React, { useState } from 'react';
    
     function NameUpdater() {
       const [name, setName] = useState("Amity");
    
       function updateName() {
         setName("AmityClev");
       }
    
       return (
         <div>
           <h2>Current Name: {name}</h2>
           <button onClick={updateName}>Update Name</button>
         </div>
       );
     }
    
     export default NameUpdater;
    

We create a functional component called NameUpdater , initilized useState hook properly inside the component to initialize the name state as "Amity", defines an updateName function that changes the name to "AmityClev". We return JSX that displays the current name and a button to update it when clicked updateName function, which updates the state.

  1. UseEffect: This hook is used to handle lifecycle components where it is been used. It runs on every render of the component when that state changes. This allows the state to be synchronized with an external system. It is used to fetch data, and directly updating the DOM. UseEffect can be pictured as instructing a friend of yours to do something when he arrives.

    For instance:

     import React, { useState, useEffect } from 'react';
    
     function ThemeToggler() {
       const [isDarkMode, setIsDarkMode] = useState(false);
    
       useEffect(() => {
         setIsDarkMode(!isDarkMode);
       }, [isDarkMode]);
    
       return (
         <div>
           <p>Current theme: {isDarkMode ? 'Dark' : 'Light'}</p>
           <button onClick={() => setIsDarkMode(!isDarkMode)}>
             Toggle Theme
           </button>
         </div>
       );
     }
    
     export default ThemeToggler;
    

We are combining the useState and useEffect here. useState, useEffect they are both React hooks imported from React. This declares a functional component named ThemeToggler. We initialize isDarkMode to false and we have which will change setIsDarkMode the state when the component renders.

The useEffect hook to run a function whenever the component renders and isDarkMode changes (due to the dependency array [isDarkMode]). We are setting isDarkMode to the opposite when the component render which will true. When clicked, the Toggle Theme state of the change to the opposite of the previous state.

useMemo: This hook is for caching the return result from the calculation, which we don’t want to be recalculated. It remembers the return value where we are using.

For Example:

import React, { useState, useMemo } from 'react';

function NumberCalculator() {
  const [number, setNumber] = useState(5);

 function updateNumber() {
    const updateN = number + 1
    setNumber(updateN);
  }


  const remmebervalue = useMemo(() => {
    console.log("Calculating square...");
    return number * number;
  }, [number]); 

  return (
    <div>
      <p>Usememo Value: {remmebervalue}</p>
     >
 <button onClick={updateNumber}>Update Number</button>
    </div>
  );
}

export default NumberCalculator;

We declare our React component and import useState and useMemo. We define our number state management const [number, setNumber] = useState(5);. Then updateNumber function to increase the number so remmebervalue the value can change when we click the Update Number button, which allows us to update the. function. remmebervalue memorized the dependence array [number].

  1. UseCallback: is used to memorise or cache, like useMemo, but it is different is used to memorise a function instead of a variable, like useMemo. It is used at the top level of the component. This hook can’t be used instead of a loop or condition. It runs only when one its dependencies is updated.

     import React, { useState, useCallback } from "react";
    
     function Counter() {
       const [count, setCount] = useState(0);
    
       const incrementCount = useCallback(() => {
         setCount((prevCount) => prevCount + 1);
       }, [count]);
    
       return (
         <div>
           <p>Count: {count}</p>
           <button onClick={incrementCount}>Increment</button>
         </div>
       );
     }
    
     export default Counter;
    

We declare our React component and import useState and useCallback. Define const [count, setCount] = useState(0); counter state. incrementCount variable is used to handle the useCallback, which houses an anonymous function that we are using to increment the counter. prevCount the previous count, while getting the previous function, we increment it by 1. We render our JSX elements to render the HTML with the button element, once it is clicked it incrementCount.

  1. UseRef: it is called at the top level of your component, useRef allows changing a mutable value state without the need to re-render. It reference to the value that does not need rendering
import React, { useState, useEffect, useRef } from "react";

function PreviousCount() {
  const [count, setCount] = useState(0);
  const prevCountRef = useRef(0); 

  useEffect(() => {
    prevCountRef.current = count;
  });

  return (
    <div>
      <p>Current Count: {count}</p>
      <p>Previous Count: {prevCountRef.current}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

export default PreviousCount;

We have a PreviousCount functional component. Define const [count, setCount] = useState(0); counter state. We initialize our useRef to the value of zero const prevCountRef = useRef(0); . We have useEffect, which renders when the component loads with dependencies. We setting the count to the prevCountRef.current = count;. When <button onClick={() => setCount(count + 1)}>Increment</button> click the count and prevCountRef.current without the need to render the component.

  1. useContext: This hook is used at the highest level of the component, which is accessible to all the components. This allows the developer to stop repeating themselves. This happens when there are nested components in the project folder structure, useContext can be used to pass data through the nested components.