⭐ React useRef hook
Intro
All use cases for useRef hook that are popular and less popular. Let's check the use cases, implementation, and how it works in React.
Prelude
When you compare the documentation and code written by developers, you can often find a completely different use for certain things.
Technology is evolving and it's really problematic to handle all use cases - especially when you are writing libs/frameworks.
A typical example of that is useRef() hook which sometimes is used by a community in a different way than described in the docs.
Yup, that's right. That hook has more than one use case.
1. useRef() in documentation
Docs explain useRef() as a hook that allows you to read real DOM data during the component life cycle. For example, if you would like to read the position of HTML div in real DOM, useRef() is the perfect tool.
1import { useLayoutEffect, useRef, useState } from "react";23export const Box = () => {4const [metadata, setMetadata] = useState<string[]>([]);56const ref = useRef<HTMLDivElement>(null);78useLayoutEffect(() => {9if (ref.current) {10// Truthy HTML node element access (not React one)11const rect = ref.current.getBoundingClientRect();1213setMetadata([14`Top: ${rect.top}`,15`Right: ${rect.right}`,16`Bottom: ${rect.bottom}`,17`Left: ${rect.left}`18]);19}20}, []);2122return (23<div ref={ref} style={{ width: "300px", height: "300px" }}>24{metadata.map((node) => (25<div key={node}>{node}</div>26))}27</div>28);29};
This is the most popular use case
2. Candidate for caching
We have a big user list that needs to be filtered by the query. This is an ideal candidate for caching. With caching - aka "flyweight" pattern - we can reduce the time complexity of the search algorithm. Of course, it increases memory usage but we're not building Mars lounger so who cares about the small amount of additional memory usage for better UX.
As you probably figured out, in our search function we have a performance bottleneck.
1import { useEffect, useState } from "react";23interface User {4username: string;5id: number;6}78const generateUsers = () =>9Array.from(10{ length: 1000 },11(_, i): User => ({ username: `User: ${i}`, id: i })12);1314export const useUsersSearch = () => {15const [users, setUsers] = useState<User[]>([]);1617const setupUsers = () => {18setUsers(generateUsers());19};2021const search = (query: string) => {22// You need caching here23const regex = new RegExp(query, "i");24setUsers((prevUsers) =>25prevUsers.filter((user) => regex.test(user.username))26);27};2829useEffect(setupUsers, []);3031return [users, search];32};
Bottleneck
3. Adding caching feature
To cache data in that case useRef() is an ideal candidate.
It's because useRef() is 100% synchronous, which means you can read/write immediately. At this point you are using something similar to class property which can be changed during the object lifecycle.
1import { useEffect, useRef, useState } from "react";23interface User {4username: string;5id: number;6}78const generateUsers = () =>9Array.from(10{ length: 1000 },11(_, i): User => ({ username: `User: ${i}`, id: i })12);1314export const useUsersSearch = () => {15const cache = useRef<Record<string, User[]>>({});16const [users, setUsers] = useState<User[]>([]);1718const setupUsers = () => {19setUsers(generateUsers());20};2122const search = (query: string) => {23// If query is in cache - return user array without search24if (cache.current.hasOwnProperty(query)) {25setUsers(cache.current[query]);26return;27}2829const regex = new RegExp(query, "i");3031setUsers((prevUsers) => {32const filteredUsers = prevUsers.filter((user) =>33regex.test(user.username)34);35cache.current[query] = filteredUsers;36return filteredUsers;37});38};3940useEffect(setupUsers, []);4142return [users, search];43};
Immediate read/write with useRef()
You have right now the same behavior as class property without a class.
4. Understanding sync vs async
Using useState() setter it can be described as request to change value. React decide when.
Changing value in useRef() it's just immediate change.
The same thing happened in your childhood when your mother asked you to take out the rubbish. It was also not an order but a request, and you did it late or not.
1import { useRef, useState } from "react";23const useCounter = () => {4const syncCounter = useRef(0);5const [asyncCounter, setAsyncCounter] = useState(0);67const asyncIncrement = () => {8// This is not an immediate change, just an async request.9console.log(asyncCounter); // 010setAsyncCounter((prevCounter) => prevCounter + 1);11console.log(asyncCounter); // 012setAsyncCounter((prevCounter) => prevCounter + 1);13console.log(asyncCounter); // 014setAsyncCounter((prevCounter) => prevCounter + 1);15console.log(asyncCounter); // 016};1718const syncIncrement = () => {19// This is an immediate change.20console.log(syncCounter.current); // 021syncCounter.current = syncCounter.current + 1;22console.log(syncCounter.current); // 123syncCounter.current = syncCounter.current + 1;24console.log(syncCounter.current); // 225syncCounter.current = syncCounter.current + 1;26console.log(syncCounter.current); // 327};28};
5. Read changes immediately
Look at handleChange() function call. We can read values immediately and they are always up to date. It's because of useRef() usage inside useForm() hook instead of useState().
The setCounter() is used only for trigger rerender - that's all.
1import { useRef, useState } from "react";23const useForm = <V extends Record<string, any>>(initValues: V) => {4// Only for rerender purposes.5const [, setCounter] = useState(0);67const values = useRef(initValues);89const rerender = () => {10// Incrementing value only for trigger rerender11setCounter((prevCounter) => prevCounter + 1);12};1314const update = <K extends keyof V>(key: K, value: V[K]) => {15values.current = { ...values.current, [key]: value }; // Immediate change16rerender(); // Triggers rerender17};1819return [values.current, update] as const;20};2122const Component = () => {23const [values, update] = useForm({ username: "" });2425const handleChange = () => {26update("username", "Example value");2728// Already updated29// No need to wait for state update30console.log(values.username);31};3233return <input value={values.username} onChange={handleChange} />;34};
No need to use useEffect()
Summary
I hope you understand useRef() power now.
Looks like someone again created a function with an unfriendly name 👽. As you saw useRef() can be used to access immediate state change, as cache and also, like an option to reading DOM data in real-time.
Feel free to contact me if you have any questions/proposals. Have a nice day and good health!







Comments
Add your honest opinion about this article and help us improve the content.