In react (before hooks) when we set state we could call a function after state had been set as such:
this.setState({}, () => {//Callback})
What is the equivalent of this with hooks?
I tried doing this
const [currentRange, setCurrentRange] = useState("24h"); setCurrentRange(someRange, () => console.log('hi'))
But this did not work
Anyone know a solution for this?
The `setState` above would throw warning and don't call `myCallback` because `useState` does not support callbacks and say that you should use `useEffect` for this purpose. So lets try to fix this in place using `useEffect` hook.
To use callback in the useState hook, we need to use the useEffect hook that triggers after state update and call the function after that. We need to pass state in the useEffect Dependency Array. useEffect is triggered when the state updates and then calls the inside function immediately.
The useCallback and useMemo Hooks are similar. The main difference is that useMemo returns a memoized value and useCallback returns a memoized function.
The React hooks equivalent of the setState callback is the useEffect hook. The useEffect hook lets us watch the change of a state. We create the count state that stores a number. Then we add the useEffect hook with a callback that runs when the count state changes.
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 ( <button onClick={() => setCurrentRange(Math.floor(Math.random() * 24) + 1 + "h")} > Change range ({currentRange}) </button> ); } ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div id="root"></div>
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