Equivalent to componentDidUpdate using React hooks
In short, you want to reset your timer when the reference of the array changes, right ?
If so, you will need to use some diffing mechanism, a pure hooks based solution would take advantage of the second parameter of useEffect
, like so:
function RefresherTimer(props) {
const [startedAt, setStartedAt] = useState(new Date());
const [timeRemaining, setTimeRemaining] = useState(getTimeRemaining(startedAt, props.delay));
//reset part, lets just set startedAt to now
useEffect(() => setStartedAt(new Date()),
//important part
[props.listOfObjects] // <= means: run this effect only if any variable
// in that array is different from the last run
)
useEffect(() => {
// everything with intervals, and the render
})
}
More information about this behaviour here https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
The useRef
creates an "instance variable" in functional component. It acts as a flag to indicate whether it is in mount or update phase without updating state.
const mounted = useRef();
useEffect(() => {
if (!mounted.current) {
// do componentDidMount logic
mounted.current = true;
} else {
// do componentDidUpdate logic
}
});