Handler ref

A handler ref is a React ref whose current property stores the latest version of an event callback. In this course, the WebSocket effect reads the callback from the ref so that updated component logic is available without recreating the connection whenever the component renders.

Minimal example

tsx
const handlerRef = useRef(onMessage);
handlerRef.current = onMessage;

socket.onmessage = (event) => {
  handlerRef.current(JSON.parse(event.data));
};

Learn this concept

Lesson 5.10 · Reconnecting WebSocket hooks

Used in exercises

Exercise 5.12 · Rider mode and customer tracking screens