6 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, there will be times when you 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.

6.1   Updating state without causing a re-render

6.1.1   Comparing useState and useRef when updating state values

6.1.2   Calling useRef

6.2   Storing timer ids with a ref

6.2.1   Introducing Presentation Mode for the BookablesList component

6.2.2   Updating the reducer to include state for Presentation Mode

6.2.3   Updating the BookablesList component to use the latest reducer

6.2.4   Managing timers for Presentation Mode with the useRef hook

6.3   Keeping references to DOM elements

6.3.1   Setting focus on an element in response to an event

6.3.2   Managing a text box via a ref

6.4   Reviewing some useRef concepts

6.5   Summary