Conteúdo do curso
React.js: Understand and Apply the Lifecycle
Sobre a Aula

Additional lifecycle methods (getDerivedStateFromProps, getSnapshotBeforeUpdate)

Class components in React have additional lifecycle methods. Two of them are getDerivedStateFromProps and getSnapshotBeforeUpdate. Let’s understand how and when to use them.

getDerivedStateFromProps

getDerivedStateFromProps is a static method. It is called before rendering the component. Its purpose is to synchronize the internal state with changes in the props. This method returns an object that updates the state or null if there are no updates.

Example:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: '' };
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.value !== prevState.value) {
      return { value: nextProps.value };
    }
    return null;
  }

  render() {
    return <div>{this.state.value}</div>;
  }
}

In this example, getDerivedStateFromProps checks if the value prop has changed. If it has, the state is updated.

getSnapshotBeforeUpdate

getSnapshotBeforeUpdate is called before the DOM is updated. It allows you to capture information from the DOM before it is changed. This method returns a value that is passed as the third argument to componentDidUpdate.

Example:

class ScrollList extends React.Component {
  constructor(props) {
    super(props);
    this.listRef = React.createRef();
  }

  getSnapshotBeforeUpdate(prevProps, prevState) {
    if (prevProps.list.length < this.props.list.length) {
      return this.listRef.current.scrollHeight;
    }
    return null;
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    if (snapshot !== null) {
      this.listRef.current.scrollTop += this.listRef.current.scrollHeight - snapshot;
    }
  }

  render() {
    return (
      <div ref={this.listRef}>
        {this.props.list.map(item => (
          <div key={item.id}>{item.text}</div>
        ))}
      </div>
    );
  }
}

Here, getSnapshotBeforeUpdate captures the scroll height before the update. componentDidUpdate uses this information to adjust the scroll after the update.

Conclusion

The getDerivedStateFromProps and getSnapshotBeforeUpdate methods are useful for efficiently managing state and DOM updates.

Use getDerivedStateFromProps to synchronize state and props. Use getSnapshotBeforeUpdate to capture information from the DOM before updates. With this, you have more control over the behavior of class components.

Entrar na conversa
Rolar para cima