useRef
is a hook used in React functional components. Use it during the following:
- When you need to interact with or persist information that is not intended for rendering or triggering re-renders of your component.
- A way to get a “stable container” that holds a mutable value throughout the lifecycle of your component, without being tied to the React rendering cycle.
Common scenarios for using useRef
1. Accessing and manipulating DOM elements directly
- a. Focusing on an input field: You get a reference to the input element and then it calls the
focus()
method. - b. Playing or pausing a video/audio element: You get a reference to the media element and call its’
play()
andpause()
methods. - c. Measuring the size or position of an element: You get a reference and use methods like
getBoundingClientRect()
. - d. Integrating with third-party libraries that manipulate the DOM: libraries like CanvasJS or some animation libraries might require direct access to a DOM node.
2. Holding mutable values that don’t trigger re-renders
- a. Storing a timer ID: you can store the ID returned by
setTimeout()
orserInterval()
so you can clear it later. - b. Keeping track of a previous state or value: unlike state, changing a ref’s
.current
value doesn’t cause the component to re-render. This can be useful for comparisons or calculations. - c. Storing a mutable object or function that needs to persist across renders: this is useful when you want to avoid recreating objects or functions unnecessarily on every render, but these values don’t directly influence what’s displayed.
When to use useState instead
useState
is for tracking state changes of a variable that intends to re-render a component.
- You need to store information that will be displayed in your component.
- Changes to the information should trigger a re-render of the component to update the UI.
useRef
- for interacting with the “outside world” of your component (ex. DOM, external APIs), or for holding mutable values that are internal implementation details and don’t affect rendering.