I run into two challenges:
1.) What is the equivalent implementation with React Hook, If I do need derived state?
Derived state for Hooks = set state conditionally and directly in the render phase:
constComp = (props) => {
const [derivedState, setDerivedState] = useState(42);
if (someCondition) {
setDerivedState(...);
}
// ...
}
This updates state without an additional commit phase as opposed to useEffect
. Above pattern is supported by React Strict Mode (no warnings):
const App = () => {
const [row, setRow] = React.useState(1);
React.useEffect(() => {
setTimeout(() => {
setRow(2);
}, 3000);
}, []);
return (
);
}
const Comp = ({ row }) => {
const [isScrollingDown, setIsScrollingDown] = React.useState(false);
const [prevRow, setPrevRow] = React.useState(null);
console.log("render, prevRow:", prevRow)
if (row !== prevRow) {
console.log("derive state");
// Row changed since last render. Update isScrollingDown.
setIsScrollingDown(prevRow !== null && row > prevRow);
setPrevRow(row);
}
return `Scrolling down: ${isScrollingDown}`;
};
ReactDOM.render( , document.getElementById("root"));
Note 1: componentWillReceiveProps
has been deprecated for quite some time. getDerivedStateFromProps
is the class components' successor in terms of derived state.
Note 2: Check preferred solutions before you resort to derived state.
2.) What if I want to do respective tasks based on multiple respective props changes?
You can either leave useEffect
deps out completely or preferably add another prop dep:
React.useEffect(() => {
return () => { };
}, [parentProp, secondProp]);