MENU
Lifecycle Methods Conversion
constructor: Function components don't need a constructor. You can initialize the state in the useState call. If computing the initial state is expensive, you can pass a function to useState.
getDerivedStateFromProps: Schedule an update while rendering instead.
shouldComponentUpdate: Use React.memo.
render: This is the function component body itself.
componentDidMount, componentDidUpdate, componentWillUnmount: The useEffect Hook can express all combinations of these (including less common cases).
getSnapshotBeforeUpdate, componentDidCatch and getDerivedStateFromError: There are still no Hook equivalents for these methods. getSnapshotBeforeUpdate is rarely needed; for error boundaries you still need a small class component (React has never shipped a function-component way to catch render errors), so most projects reach for a community package such as react-error-boundary instead of writing one from scratch.
To implement the functionality of getDerivedStateFromProps, you can update the state right during rendering, eg.:
RESETRUNFULL
<!DOCTYPE html><html><head>
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head><body>
<div></div>
<script type="text/babel">
const { useState } = React;
function ScrollView({row}) {
const [isScrollingDown, setIsScrollingDown] = useState(false);
const [prevRow, setPrevRow] = useState(null);
if (row !== prevRow) { // Row changed since last render. Update isScrollingDown.
setIsScrollingDown(prevRow !== null && row > prevRow);
setPrevRow(row);
}
return `Scrolling down: ${isScrollingDown}`;}
function App() {
const [row, setRow] = useState(0);
return (
<React.Fragment>
<button onClick={() => setRow(r => r + 1)}>row++</button>
<button onClick={() => setRow(r => r - 1)}>row--</button>
<p><ScrollView row={row}/></p>
</React.Fragment>
);
}
const root = ReactDOM.createRoot(document.querySelector("div"));
root.render(<App/>);
</script>
</body></html>