Check new and old props and react outside componentwillreceiveprops

In React, when a component receives new props, it's not guaranteed that the component will re-render immediately. This is because React uses a virtual DOM (a lightweight in-memory representation of the real DOM) to optimize rendering.

When a component receives new props, React will update the virtual DOM, but it won't necessarily re-render the component immediately. Instead, React will schedule a re-render for the component at some point in the future.

This is known as "batching" or "async rendering". React batches updates to the virtual DOM to improve performance by reducing the number of DOM mutations.

Now, let's talk about componentWillReceiveProps (which is deprecated in React 16.3 and later) and getDerivedStateFromProps.

componentWillReceiveProps (deprecated)

componentWillReceiveProps is a lifecycle method that was used to handle prop updates. It was called whenever the component received new props. However, it's deprecated in React 16.3 and later, and you should avoid using it.

getDerivedStateFromProps

getDerivedStateFromProps is a lifecycle method that's used to handle prop updates. It's called whenever the component receives new props, and it returns an object with the updated state.

Here's an example:

class MyComponent extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.prop1!== prevState.prop1) {
      return { prop1: nextProps.prop1 };
    }
    return null;
  }

  render() {
    return <div>Prop 1: {this.props.prop1}</div>;
  }
}

In this example, when prop1 changes, getDerivedStateFromProps is called, and it returns an object with the updated prop1 value. The component's state is then updated accordingly.

React outside of componentWillReceiveProps

When you need to perform some action outside of the component's render method, you can use useEffect or useLayoutEffect hooks.

useEffect is used to perform side effects, such as making API calls or setting timers. It's called after the component has been rendered.

useLayoutEffect is similar to useEffect, but it's called after the component has been rendered and the layout has been updated.

Here's an example:

import { useEffect } from 'react';

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

  useEffect(() => {
    // Perform some action when prop1 changes
    console.log(`Prop 1 changed to ${this.props.prop1}`);
  }, [this.props.prop1]);

  render() {
    return <div>Prop 1: {this.props.prop1}</div>;
  }
}

In this example, when prop1 changes, useEffect is called, and it logs a message to the console.

In summary: