useRef Hook() :-
ref does not cause your component to re update when it gets changed.
- part1 Source Code:-
import { useState, useEffect, useRef } from 'react'
export default function App() {
const [name, setName] = useState("");
// const [renderCount, setRenderCount] = useState(-2);
// useEffect(() => {
// console.log("inside useEffect");
// setRenderCount(prevRenderCount => prevRenderCount + 1);
// }, [name])
const renderCount = useRef(0);
useEffect(() => {
console.log("inside useeffect");
renderCount.current += 1
})
const inputRef = useRef();
return (
<>
<input type="text" value={name} onChange={(e) => setName(e.target.value)} />
<div> My name is {name}. </div>
{/* <div> {renderCount.current} </div> */}
<button> {renderCount.current} </button>
</>
)
}
Output Image :-
2.Part2 Source Code:-
import { useState, useEffect, useRef } from 'react'
export default function App() {
const [name, setName] = useState("");
// const [renderCount, setRenderCount] = useState(-2);
// useEffect(() => {
// console.log("inside useEffect");
// setRenderCount(prevRenderCount => prevRenderCount + 1);
// }, [name])
const renderCount = useRef(0);
useEffect(() => {
console.log("inside useeffect");
renderCount.current += 1
})
const inputRef = useRef();
return (
<>
<input ref={inputRef} onClick={() => console.log("clicked")} type="text" value={name} onChange={(e) => setName(e.target.value)} />
<div> My name is {name}. </div>
{/* <div> {renderCount.current} </div> */}
<button onClick={() => {
inputRef.current.click()
}}> {renderCount.current} </button>
</>
)
}
Output Image:-
3.Part3 Source Code:-
import {useEffect, useRef, useState} from 'react'
export default function App() {
const [name, setName] = useState("");
const PrevName = useRef("")
useEffect(() => {
console.log('name', name);
console.log('PrevName.current1', PrevName.current);
PrevName.current = name
console.log('PrevName.current2', PrevName.current);
})
return (
<>
<input type="text" onChange={(e) => setName(e.target.value)} />
<div>{name} - {PrevName.current}</div>
</>
)
}
Top comments (0)