Sunday, 29 September 2024

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    





 

        




No comments:

Post a Comment

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 ...