useRef Hook
What is Use Ref hook?
It is a react hook which persists state between re-renders, similar to useState(), but when we update the useRef variable it doesn't cause re - render, whereas when we set the useState variable it causes re - render.
Let's understand this with an example :
Let's take an example where we are typing our name and we want to see how many times that re - renders our screen. So every time we type a character it'll re - render the component.
const [name, setName] = useState('')
const [renderCount , setRenderCount] = useState(0)
useEffect ( () => {
setRenderCount( prevRenderCount => prevRenderCount + 1 )
})
return (
<>
<input value={name} onChange={e => setName(e.target.value)} />
<div> My name is {name} </div>
<div> I rendered {renderCount} times </div>
</>
)
Here we are using useState to handle the name state. When we type in input field it will change the state which in turn trigger the setName function which will cause a re - render.
So to count each re - render we use useEffect hook without any dependency array which will cause it to run after completion of every re - render and after every re - render we will update the state of renderCount variable and we will get the number of re - renders.
Except we wouldn't.
See that we are updating the renderCount variable everytime re - render occurs and we set the state, but it will in turn cause another re - render here due to setting of state. And this will run the useEffect again , which will again set the state and it will cause an infinite loop.
So what's the solution?
Here comes useRef to the rescue. We will use useRef variable to count the re - renders.
const [name, setName] = useState('')
const renderCountRef = useRef(1)
useEffect ( () => {
renderCountRef.current = renderCountRef.current+ 1;
})
return (
<>
<input value={name} onChange={e => setName(e.target.value)} />
<div> My name is {name} </div>
<div> I rendered {renderCountRef.current} times </div>
</>
)
So useRef return an object with the initialized value. Here we have initialized renderCountRef variable with 1, so it will return { current : 1 } object. And whenever we have to update the state we just access this current property and change it's value also to access it we do the same. useRef is completely separate from our component render cycle.
Conclusion
useRefsimilar touseStatepersist variable between re - renders.It does not cause re - render when update the variable.
It return an object
{ current : initializedValue }instead of a function likeuseState.We access this current property when trying to access the variable value or change it.