Sunday, 29 September 2024

React Hooks - useMemo

 v useMemo Hook

Ø The React useMemo Hook returns a memoized value.

 

Ø It’s like caching a value so that it doesn't need to be recalculated.

 

Ø The useMemo Hook only runs when one of its dependencies update. This can improve performance.

 

Ø The useMemo and useCallback Hooks are similar. The main difference is that useMemo returns a memoized value and useCallback returns a memoized function.

 

Ø The useMemo Hook can be used to keep expensive, resource intensive functions from needlessly running.

 

Example: 1 Why we need useMemo Hook (Problem without useMemo Hook)

import React, { useState } from ‘react’

import ‘./App.css’

 

function App() {

           const [number, setNumber] = useState(0)

           const [counter, setCounter] = useState(0)

 

           function cubeNum(num) {

            console.log(‘Calculation done!’);

            return Math.pow(num,3)

}

const  result  = cubeNum(number);

return (

            <>

<input type=”number” value={number} onChange={(e)=>{setNumber(e.target.value)}} />

            <h1>Cube of the number : {result}</h1>

<button onClick={()=>{setCounter(counter+1)}}>

Counter++</button>

<h1>Counter : { counter }</h1>

</>

)

}

export default App; 

so if you are click on Counter++ button then also it will called cubeNum method, because of when we update the counter ,changes the counter number, it re-render web page, it recalculate cube.so to prevent the function to recalculate cube, we can use useMemo hook.



import React, { useState, useMemo } from ‘react’

import ‘./App.css’

 

function App() {

           const [number, setNumber] = useState(0)

           const [counter, setCounter] = useState(0)

 

           function cubeNum(num) {

            console.log(‘Calculation done!’);

            return Math.pow(num,3)

}

//const  result  = useMemo(()=> {return cubeNum(number)},[number]);

const  result  = useMemo(() => cubeNum(number),[number]);

return (

            <>

<input type=”number” value={number} onChange={(e)=>{setNumber(e.target.value)}} />

            <h1>Cube of the number : {result}</h1>

<button onClick={()=>{setCounter(counter+1)}}>

Counter++</button>

<h1>Counter : { counter }</h1>

</>

)

}

export default App;

 

    When click on Counter++ button

    When 3 entered in textbox ,then only called cubeNum method



React Hooks - useRef

        Ø useRef is a react Hook that allows us to create mutable variableswhich will not re-render the component.

Ø The useRef Hook allows you to persist values between renders.

Ø It can be used to store a mutable value that does not cause a re-render when updated.

Ø It can be used to access a DOM element directly.

Ø useRef() only returns one item.

Ø It returns an Object called Current

Example:1 update count value

    Below example shows that if you use useEffect then it will goes infinite loop.

 

import React, {useState} from ‘react’;

import ‘./App.css’;

 

function App() {

           const [value, setValue] = useState(0);

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

          

           useEffect(() => {

            setCount(prev=> prev+1)

})

          

           return (

                       <>

<button onClick={()=>{setValue(prev => prev-1)}}>-1</button>

                       <h1>{value}</h1>

<button onClick={()=>{setValue(prev => prev+1)}}>+1</button>

<h1>Component Render Count: {count}</h1>

</>

)

 }

To avoid above issue use useRef hook

import React, {useState, useRef } from ‘react’;

import ‘./App.css’;

 

function App() {

           const [value, setValue] = useState(0);

           const count = useRef(0);

 

           useEffect(() => {

            count.current=count.current+1;

});

 

           return (

                       <>

<button onClick={()=>{setValue(prev => prev-1)}}>-1</button>

                       <h1>{value}</h1>

<button onClick={()=>{setValue(prev => prev+1)}}>+1</button>

<h1>Component Render Count: {count.current}</h1>

</>

)

 }




Example :: 2

import React, {useState, useRef } from ‘react’;

import ‘./App.css’;

 

function App() {

           const [value, setValue] = useState(0);

           const inputElement = useRef();

 

           const btnClicked = () =>{

            console.log(inputElement.current);

            inputElement.current.style.background=”blue”;

}

 

           return (

                       <>

<input type=”text”  ref={ inputElement }/>

<button onClick={btnClicked}>Click Here</button>

</>

)

 }

 

 After use console.log(inputElement);


    After use console.log(inputElement.current);



    After apply style with background color to blue    





 

        




Sunday, 22 September 2024

React Hooks - useEffect

Ø The useEffect Hook allows you to perform side effect in your components. 

Ø Side effects include fetching data, directly updating the DOM and timers like setTimeout and setInterval.

                 Ø useEffect accepts two arguments. The second argument is optional
                
            useEffect(<Callback function>, <dependency>)

        Ø  Whenever useEffect use without any dependency then it will                       execute callback function on every render whenever any  state                           change in component. 

Ø  Whenever useEffect use with empty array then it will execute callback function only once whenever component gets loaded. 

Ø  Whenever useEffect use with dependency then it will execute callback function whenever component gets loaded and after that dependency changes again it will execute callback function.

            Example : 1 useEffect without/With/EmptyArray any                                 dependency

            
import React, { useEffect, usestate } from 'react'

            import './App.css'

 

function App()  {

const [count, setCount] = usestate(0)

const [name, setName] = useState(“Hello”)

 

/*Without dependency - Runs on every render*/

useEffect(() => {

            setTimeout(()=>{

            setCount(count => count+1);

},2000)

}) 

/*Empty array - runs only on first render*/

/*useEffect(() => {

            setTimeout(()=>{

            setCount(count => count+1);

},2000)

},[])*/

 

/*With dependency - runs on first render and anytime when it's dependency                 value changed*/

/*useEffect(() => {

            setTimeout(()=>{

            setCount(count => count+1);

},2000)

},[count,name])*/

 

return (

<> 

<h1>I've rendered {count) times!</h1>

</>

)

}

export default App

O/P

Without Dependency




Empty Array []








With Dependency




Note:- To continue increasing the count, remove React.StrictMode from App.js, it will do an additional run time check in the development environment to make sure that your react app is safe





React Hooks - custom Hook

  v CustomHook Ø React allows us to create our own hook which is known as custom hook. Example – 1 localStorage Demo Step-1 Create ...