In react (before hooks) when we set state we could call a function after state had been set as such:
this.setState({}, () => {//Callback})
W
The useEffect hook can be used to invoke a function when some state change. If you pass it currentRange
in an array as second argument, the function will only be invoked when currentRange
change.
You can also create your own custom hook that uses the useRef hook to keep track of if it's the first time the effect is being run, so that you can skip the first invocation.
Example
const { useRef, useState, useEffect } = React;
function useEffectSkipFirst(fn, arr) {
const isFirst = useRef(true);
useEffect(() => {
if (isFirst.current) {
isFirst.current = false;
return;
}
return fn();
}, arr);
}
function App() {
const [currentRange, setCurrentRange] = useState("24h");
useEffectSkipFirst(
() => {
console.log("hi");
},
[currentRange]
);
return (
);
}
ReactDOM.render( , document.getElementById("root"));