Article thumbnail

React useRef hook

6m
hooks
api

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.

typescript
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.

1
import { useLayoutEffect, useRef, useState } from "react";
2
3
export const Box = () => {
4
const [metadata, setMetadata] = useState<string[]>([]);
5
6
const ref = useRef<HTMLDivElement>(null);
7
8
useLayoutEffect(() => {
9
if (ref.current) {
10
// Truthy HTML node element access (not React one)
11
const rect = ref.current.getBoundingClientRect();
12
13
setMetadata([
14
`Top: ${rect.top}`,
15
`Right: ${rect.right}`,
16
`Bottom: ${rect.bottom}`,
17
`Left: ${rect.left}`
18
]);
19
}
20
}, []);
21
22
return (
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.

1
import { useEffect, useState } from "react";
2
3
interface User {
4
username: string;
5
id: number;
6
}
7
8
const generateUsers = () =>
9
Array.from(
10
{ length: 1000 },
11
(_, i): User => ({ username: `User: ${i}`, id: i })
12
);
13
14
export const useUsersSearch = () => {
15
const [users, setUsers] = useState<User[]>([]);
16
17
const setupUsers = () => {
18
setUsers(generateUsers());
19
};
20
21
const search = (query: string) => {
22
// You need caching here
23
const regex = new RegExp(query, "i");
24
setUsers((prevUsers) =>
25
prevUsers.filter((user) => regex.test(user.username))
26
);
27
};
28
29
useEffect(setupUsers, []);
30
31
return [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.

1
import { useEffect, useRef, useState } from "react";
2
3
interface User {
4
username: string;
5
id: number;
6
}
7
8
const generateUsers = () =>
9
Array.from(
10
{ length: 1000 },
11
(_, i): User => ({ username: `User: ${i}`, id: i })
12
);
13
14
export const useUsersSearch = () => {
15
const cache = useRef<Record<string, User[]>>({});
16
const [users, setUsers] = useState<User[]>([]);
17
18
const setupUsers = () => {
19
setUsers(generateUsers());
20
};
21
22
const search = (query: string) => {
23
// If query is in cache - return user array without search
24
if (cache.current.hasOwnProperty(query)) {
25
setUsers(cache.current[query]);
26
return;
27
}
28
29
const regex = new RegExp(query, "i");
30
31
setUsers((prevUsers) => {
32
const filteredUsers = prevUsers.filter((user) =>
33
regex.test(user.username)
34
);
35
cache.current[query] = filteredUsers;
36
return filteredUsers;
37
});
38
};
39
40
useEffect(setupUsers, []);
41
42
return [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.

1
import { useRef, useState } from "react";
2
3
const useCounter = () => {
4
const syncCounter = useRef(0);
5
const [asyncCounter, setAsyncCounter] = useState(0);
6
7
const asyncIncrement = () => {
8
// This is not an immediate change, just an async request.
9
console.log(asyncCounter); // 0
10
setAsyncCounter((prevCounter) => prevCounter + 1);
11
console.log(asyncCounter); // 0
12
setAsyncCounter((prevCounter) => prevCounter + 1);
13
console.log(asyncCounter); // 0
14
setAsyncCounter((prevCounter) => prevCounter + 1);
15
console.log(asyncCounter); // 0
16
};
17
18
const syncIncrement = () => {
19
// This is an immediate change.
20
console.log(syncCounter.current); // 0
21
syncCounter.current = syncCounter.current + 1;
22
console.log(syncCounter.current); // 1
23
syncCounter.current = syncCounter.current + 1;
24
console.log(syncCounter.current); // 2
25
syncCounter.current = syncCounter.current + 1;
26
console.log(syncCounter.current); // 3
27
};
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.

1
import { useRef, useState } from "react";
2
3
const useForm = <V extends Record<string, any>>(initValues: V) => {
4
// Only for rerender purposes.
5
const [, setCounter] = useState(0);
6
7
const values = useRef(initValues);
8
9
const rerender = () => {
10
// Incrementing value only for trigger rerender
11
setCounter((prevCounter) => prevCounter + 1);
12
};
13
14
const update = <K extends keyof V>(key: K, value: V[K]) => {
15
values.current = { ...values.current, [key]: value }; // Immediate change
16
rerender(); // Triggers rerender
17
};
18
19
return [values.current, update] as const;
20
};
21
22
const Component = () => {
23
const [values, update] = useForm({ username: "" });
24
25
const handleChange = () => {
26
update("username", "Example value");
27
28
// Already updated
29
// No need to wait for state update
30
console.log(values.username);
31
};
32
33
return <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!

I create content regularly!

I hope you found my post interesting. If so, maybe you'll take a peek at my LinkedIn, where I publish posts daily.

Comments

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

created: 01-06-2022
updated: 16-10-2022