user944513
user944513

Reputation: 12729

how to receive updated props in react js?

could you please tell me how to receive updated props in react js ?.I know componentWillReceiveProps is unsafe and I tried using getDerivedStateFromProps but not work

here is my code https://codesandbox.io/s/rm30zoonk4

After two second I am updating my state which is passing to props

Expected output after two second

abcsssss

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

Upvotes: 1

Views: 3787

Answers (2)

CoderXYZ
CoderXYZ

Reputation: 167

You should use componentDidUpdate(prevProps, prevState)

componentDidUpdate is invoked anytime the component is about the receive new props or internal state, here you can intervene before the component is rerendered.

So in hello.js, instead of getDerivedState:

componentDidUpdate(prevProps) {
  if (prevProps.src !== this.props.src) {
    this.test()
  }
}

the comparison "if (prevProps.src !== this.props.src)" is done so the component only update if the src prop changed, preventing unnecessary rerenders.

Upvotes: 1

wdm
wdm

Reputation: 7189

You can use componentDidUpdate

componentDidUpdate() is invoked immediately after updating occurs.

https://reactjs.org/docs/react-component.html#componentdidupdate

class Hello extends Component {
    state = {
        name: ""
    }
    componentDidUpdate(prevProps) {
        if (this.props.src !== prevProps.src) {
            this.setState({name: this.props.src + 'ssss'});
        }
    }
    render() {
        return <div>{this.state.name}</div>;
    }
}

Upvotes: 1

Related Questions