Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

useState hook with callback

const [state, setState] = useState(null);
const myCallbacksList = useRef([]);
const setStateWithCallback= (newState, callback) => {
  setState(state);
  if(callback) myCallbackList.current.push(callback)
}
useEffect(() => {
  myCallbacksList.current.forEach((callback) => callback())
  myCallbacksList.current = [];
}, [state]);
…
setStateWithCallback(newState, myCallback)
Source by maksimrv.medium.com #
 
PREVIOUS NEXT
Tagged: #useState #hook #callback
ADD COMMENT
Topic
Name
2+1 =