Refs and the DOM

Refs provide a way to access DOM nodes or React elements created in the render method.

In typical React dataflow, props are the only way thar parent components interact with their children. To modify a child, you re-render it with new props.

However there are few cases where you need to imperatively modify a child outside of the typical dataflow. The child to be modified could be an instance of a React component, or it could be a DOM element. For both of these cases, React provides an escape hatch.

When to Use Refs

There are a few good use cases for refs:

  • Managing focus, text selection, or media playback.
  • Triggering imperative animations.
  • Integrating with third-party DOM libraries.
  • Persisitng values between renders in functions.

// useEffect(() => { prevName.current = name },[name])

// get the prevname {prevName.current}

Avoid using refs for anything that can be done declaratively.

For example, instead of exposing open() and close() methods on a Dialog component, pass an isOpen prop to it

Don’t Overuse Refs

Your first inclination may be to use refs to “make things happen” in your app. If this is the case, take a moment and think more critically about where state should be owned in the component hierarchy.

// example from ref2 in hooks-app

function focus(){
    inputRef.current.focus()
    inputref.current.value = 'XXX' // Don't do because of that the state is not updating
}