React

useRef

useRef is also a way to keep the values of variables unchanged when the component renders. But unlike useMemo or useCallback, useRef doesn't have dependencies array and the value will persist for the full lifetime of the component. You can think useRef is like a "box" that can hold a mutable value in it.

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue)

// Call signature
const ref = useRef(initialValue)

// access ref.current for current value

Common Usage

Although useRef can be used in different cases but the most common use case is to access a child imperatively

function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<Button onClick={onButtonClick}>Focus the input</Button>
<input ref={inputEl} type="text" />
</>
);
}

Uncommon usage

function TextInputWithFocusButton() {
const typingTimeout = useRef(null);
const [searchString, setSearchString] = useState("Search string appears here")
// simple debounce
const handleInputChange = (e) => {
clearTimeout(typingTimeout.current)
typingTimeout.current = setTimeout(() => {
setSearchString(e.target.value)
}, 800)
};
return (
<>
<input
type="text"
onChange={handleInputChange}
placeholder="Search"
/>
<p>{searchString}</p>
</>
);
}

Note

Keep in mind that useRef doesn't notify you when its content changes. Mutating the .current property also doesn't cause a re-render.

Previous
useCallback