DEV Community

Vijay Kumar
Vijay Kumar

Posted on

React Hooks Short Notes

React hooks have revolutionised the way we manage state and lifecycle methods in react, introducted in React 16.8 version. They allow to write state and other features in functional components without writing it in class components .

The main advantage it has increased code readability and reusability with stateful logic in functional components.


Hooks are broadly classified into buiult in type hooks and custom hooks.

Let's explore the builtin hooks in detail which are commonly used in projects :

  • 1. useState - This hook allows functional components to have state variables. It returns a statevalue and updates the function with this value .

import {useState} from "react";

function Counter(){
const(count,setCount)=useState(0);

return(
<div>
<p> ON clicking the button it increments the {count} counter by 1</p>
<button onClick={()=>setCount(count+1)}>Increment</button>
</div>
);
}
Enter fullscreen mode Exit fullscreen mode

  • 2. useEffect - Used for handling side effects API Requests, Data Fetching and manually handling DOM.
import {useState,useEffect} from "react";

function DataFetcher(){
const(data,setData)=useState(null);

useEffect(()=>{
fetch("https://api.com/data")
then.(response=>response.json())
then.(data=>setData(data));
},[]);

return <div>{data ?JSON.stringify(data) : "Loading now"}</div>;
}
Enter fullscreen mode Exit fullscreen mode

  • 3.useRef - Useful in accessing DOM Elements and persisting values across renders without triggering re-renders.

  • 4.useMemo - Optimises performance by memoizing the values and avoiding unnecessary recalculations .

  • 5.useCallbacks - This memoises functions to prevent unnecessary recreations .

  • 6.useReducer - useful for handling complex state logic which is similar to useState and pass multiplt actions statefully.

  • Custom Hooks - You can create custom hooks to handle and reuse stateful logic across components.

React Hooks simplify component logic and improve reusability making React development more efficient.

Top comments (0)