5 Managing component state with the useRef hook

 

This chapter covers

  • Calling the useRef hook to obtain a ref
  • Updating a ref by assigning values to its current property
  • Updating state without triggering re-renders
  • Setting the ref attribute in JSX to assign DOM element references to a ref
  • Accessing DOM element properties and methods via a ref

While most of the values stored by your component will be directly represented in the user interface of your application, sometimes you’ll use a variable only for the mechanics of your app rather than for consumption by users. You may want to use setTimeout or setInterval as part of an animation, so you need to keep hold of the IDs they return. Or you may want to work with DOM form elements as uncontrolled inputs, so you need to keep hold of references to those elements. Either way, you may not need to display these values to the user, and so changing them shouldn’t automatically trigger a re-render.

5.1 Updating state without causing a re-render

5.1.1 Comparing useState and useRef when updating state values

5.1.2 Calling useRef

5.2 Storing timer IDs with a ref

5.3 Keeping references to DOM elements

5.3.1 Setting focus on an element in response to an event

5.3.2 Managing a text box via a ref

Summary