react-reuse-hooks
Version:
A collection of 30+ production-ready reusable React hooks for web apps, covering state, effects, media, forms, and utilities.
21 lines (16 loc) • 504 B
JavaScript
import { useEffect, useRef, useState } from "react";
export function useStateWithCallback(initialState) {
const [state, setState] = useState(initialState);
const callbackRef = useRef(null);
const updateState = (newState, callback) => {
callbackRef.current = callback;
setState(newState);
};
useEffect(() => {
if (callbackRef.current) {
callbackRef.current(state);
callbackRef.current = null;
}
}, [state]);
return [state, updateState];
}