Approach 1. With useEffect
With React 16.x and up, if you want to invoke a callback function on state change using useState
hook, you can use the useEffect
hook to listen to the state change.
1 | import React, { useState, useEffect } from 'react'; |
Or you can wrap it in a helper function:
1 | const useStateCallback = (initilValue, callback) => { |
Note:
- The callback function will be called on initial render.
- The callback function won’t trigger if the state is identical.
Approach 2. With useEffect
and useRef
setState(updater, callback)
fro useState
Following implementation comes really close to the original setState
callback of classes.
- Callback execution is omitted on initial render - we only want to call it on state updates
- Callback can be dynamic for each
setState
invocation, like with classes
Usage
1 | const App = () => { |
useStateCallback
1 | function useStateCallback(initialState) { |
Ref: