useRef
The useRef has two purposes:
- It can be used to access a DOM element directly.
- Hook allows you to persist values between renders so it can be used to store a mutable value that does not cause a re-render when updated.
1. Access DOM Element
import { useState, useRef } from "react";
const ObjectRef = () => {
const [input1, setInput1] = useState("")
const [input2, setInput2] = useState("")
const inputElement = useRef();
const focusInput = () => {
inputElement.current.focus();
};
return (
<div className="box">
<h1>Object Ref</h1>
<input type="text" ref={inputElement} value={input1}
onChange={ (e) => setInput1(e.target.value)} />
<input type="text" value={ input2 }
onChange={ (e) => setInput2(e.target.value)}/>
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
export default ObjectRef;
Breakdown
- line 7: create a
Ref(reference) - line 9 - 11:
useRefreturns only 1 element:currentand we can access and modify that element accordingly. In this case we call the.focus()method to effectively set the focus on the input field - line 17: we add the
ref={ inputRef }as a property to the element (or Component) - line 23: the
onClick-event fires that function to update the ref.
2. Persist Values
import { useState, useEffect, useRef } from "react"
const PreviousState = () => {
const [input, setInput] = useState("")
const previousValue = useRef("")
useEffect( () => {
previousValue.current = input
}, [input])
return(
<div className="box">
<h1>Previous State</h1>
<input type="text"
value={ input }
onChange={ (e) => setInput(e.target.value)}/>
<div>
<h3>Current value: { input }</h3>
<h3>Previous value: { previousValue.current }</h3>
</div>
</div>
)
}
export default PreviousState
Breakdown
- line 6: create a
Ref(reference) - line 8 - 10: the
useEffect-hook updates the value of therefwhen the state of[input]changes (in this case every time we enter data) - So on each render
previousValue.currentcontains the information from the previous state.