Refs Flashcards

1
Q

What are refs?

A

Refs provide a way to access DOM nodes or React elements created in the render method. They’re a way to reference elements on the page because one of the golden rules of react is that you don’t touch the DOM.

In the typical React dataflow, props are the only way that parent components interact with their children. To modify a child, you re-render it with new props. However, there are a 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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

When to use refs?

A

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.

Avoid using refs for anything that can be done declaratively.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Don’t overuse refs

A

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. Often, it becomes clear that the proper place to “own” that state is at a higher level in the hierarchy

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Creating refs

A

Refs are created using React.createRef() and attached to React elements via the ref attribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div></div>;
  }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Accessing refs

A

When a ref is passed to an element in render, a reference to the node becomes accessible at the current attribute of the ref.

const node = this.myRef.current;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

The value of ref differs depending on the type of the node

A
  • When the ref attribute is used on an HTML element, the ref created in the constructor with React.createRef() receives the underlying DOM element as its current property.
  • When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current.
  • You may not use the ref attribute on function components because they don’t have instances.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly