Skip to content

Instantly share code, notes, and snippets.

@orenmizr
Created April 30, 2021 18:56
Show Gist options
  • Save orenmizr/3af3dc4a771ebb7bcde765c16d7df0bb to your computer and use it in GitHub Desktop.
Save orenmizr/3af3dc4a771ebb7bcde765c16d7df0bb to your computer and use it in GitHub Desktop.
useStateCallback.js
import { useState, useEffect, useRef, useCallback } from 'react';
export default (initialState) => {
const [state, setState] = useState(initialState);
const cbRef = useRef(null);
const setStateCallback = useCallback((state, cb) => {
cbRef.current = cb;
setState(state);
}, []);
useEffect(() => {
if (cbRef.current) {
cbRef.current(state);
cbRef.current = null;
}
}, [state]);
return [state, setStateCallback];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment