Skip to content

Instantly share code, notes, and snippets.

@honzabrecka
Created June 7, 2020 21:18
Show Gist options
  • Save honzabrecka/ed5b3465196f9a1cea502d1c95cfa6e8 to your computer and use it in GitHub Desktop.
Save honzabrecka/ed5b3465196f9a1cea502d1c95cfa6e8 to your computer and use it in GitHub Desktop.
export function useCallbackInNextRender() {
const [value, set] = useState(null);
useSafeEffect(
(safetyGuard) => {
if (!value) return;
const [callback, args] = value;
callback(safetyGuard, ...args);
},
[value]
);
return useCallback((callback, ...args) => {
set([callback, args]);
}, []);
}
function App() {
const [state, setState] = useState({ a: 1, b: 2});
const submit = useCallback(() => {
console.log(state);
}, [state]);
const setDelayedSubmit = useCallbackInNextRender();
const onChange = useCallback((name, value) => {
// setState is async, therefore it's not possible to read updated value right back
setState(state => ({ ...state, [name]: value }));
// submit(); // it won't work as state might not (and won't) be updated yet
// so it's delayed until next "render"
setDelayedSubmit(submit);
}, []);
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment