- Normal variables are reset to their initial value(recreated) when the component rerenders(state updates).
- If the state updates, then it forces the component to re-render(re-execute) the component.
useRef:
- A built-in hook helps to persist values between renders, but does not re-render the component by any chance.
- useRef returns a reference that is a plain JavaScript object with a special property called current.
- ref value is persisted between render cycles, just like state variables, but the component is not re-rendered when the ref changes.
- It is a combination of Normal variables and state variables.
- useRef hook accepts an optional argument, which can be of any valid JavaScript value that is the initial value for the reference that it returns.
keypoints :
useRef returns an object with a special property called current.
Updating the reference value doesn't cause a re-render of the component.
useEffect side effect cannot be controlled using useRef variables.useEffect callback can only be controlled using state or props.
example :
function App{
const inputRef=useRef()
useEffect(()=>{
inputRef.current.focus();
})
return(
<div>
<input type="text" onChange={e=>setState(e.target.value)} ref={inputRef}/>
</div>
) }
Use case:
- if you want to clear the setInternals, then you need a reference for that particular setInternals, but the scope is within the useEffect so you need a ref. You can use ref for setInternals to clear that internal when a button is clicked or else.