From the course: Master React 19 and Next.js 16 with Hands-On Projects and Real-World Applications

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

Reference values with refs review: Common mistakes and best practices

Reference values with refs review: Common mistakes and best practices

From the course: Master React 19 and Next.js 16 with Hands-On Projects and Real-World Applications

Reference values with refs review: Common mistakes and best practices

Welcome back! In this session, we're reviewing everything from the reference values with refs chapter. Refs are special in React. Unlike state, updating a ref does not trigger a re-render. Here you see a simple example. Use ref 0 starts with 0. Each click increases clicks.current and we log it to the console. The UI doesn't update because refs don't cause re-renders. This makes refs great for values we want to keep between renders without affecting the DOM. Let's build on this idea with a timer. Here we use useRef to store an interval ID. If we used a normal variable, React would reset it on every render. With a ref, the value persists. This prevents creating multiple timers. This example shows a common best practice. Use refs to store values that persist across renders but don't affect UI updates, like interval IDs. Now let's move from values to accessing DOM nodes. Here we create the ref. Then we attach it to the element using the ref attribute. Then we use it. A common mistake is…

Contents