React 16.3.0 was released and there were changes in React lifecycles.
React does not recommend to use componentWillMount
, componentWillReceiveProps
, componentWillUpdate
.
In that case, what should I use instead of componentWillUpdate
?
For example, in the following code how can I replace componentWillUpdate
?
import React from "react";
import Modal from "./Modal";
class ModalContainer extends React.Component {
state = {
openModal: false
};
onClick = () => {
this.setState({
openModal: !this.state.openModal
});
};
escapeKey = e => {
if (e.key === "Escape" && this.state.openModal === true) {
this.setState({
openModal: !this.state.openModal
});
}
};
componentDidMount() {
document.body.classList.add("no-scroll");
this.componentWillUpdate(this.state, this.state);
}
componentWillUpdate(p, c) {
if (c.openModal) {
window.addEventListener("keyup", this.escapeKey);
} else {
window.removeEventListener("keyup", this.escapeKey);
}
}
componentWillUnmount() {
window.removeEventListener("keyup", this.escapeKey);
}
render(props) {
return (
<div className="ModalContainer">
<a className={`ModalContainer-trigger`} onClick={this.onClick}>
click here to open the modal
</a>
{this.state.openModal && (
<Modal
onClick={this.onClick}
in={!!this.state.openModal}
{...this.props}
/>
)}{" "}
</div>
);
}
}
export default ModalContainer;
Thank you
The componentWillUpdate() method has been deprecated in the latest releases of React as per this issue. It is suggested to use getSnapshotBeforeUpdate() method as its alternative but if we still want to use componentWillUpdate() we can do it by calling it as UNSAFE_componentWillUpdate().
The function is replaced with class constructor But with the release of class syntax, you can use the constructor method to initialize state value and bind event handlers. As ES6 classes became the main style of writing React components, the use of componentWillMount became unnecessary.
getDerivedStateFromProps is one of those newly introduced lifecycle method replacing componentWillReceiveProps , which has now become UNSAFE_componentWillReceiveProps .
ReactJS – componentWillUpdate() Method This method is used during the updating phase of the React lifecycle. This function is generally called before the component is updated or when the state or props passed to the component changes.
Take a look at getSnapshotBeforeUpdate
https://reactjs.org/docs/react-component.html#getsnapshotbeforeupdate
getSnapshotBeforeUpdate() is invoked right before the most recently rendered output is committed to e.g. the DOM. It enables your component to capture some information from the DOM (e.g. scroll position) before it is potentially changed.
Btw, I think there's not much use case to use such method.
You can still use componentDidUpdate
if you want to have side effects after any states changed.
This answer based on React16.6.3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With