useFreshRef
Aboutβ
Avoid stale state in callbacks with this hook. Auto updates values using a ref.
Installationβ
npm install --save rooks
Importing the hookβ
import { useFreshRef } from "rooks";
Usageβ
function Demo() {
const [value, setValue] = useState(5);
function increment() {
setValue(value + 1);
}
const freshIncrementRef = useFreshRef(increment);
useEffect(() => {
function tick() {
freshIncrementRef.current();
}
const intervalId = setInterval(tick, 1000);
return () => {
clearInterval(intervalId);
}
}, []);
return null;
}
render(<Demo />);
Argumentsβ
Argument value | Type | Description |
---|---|---|
value | T | The value which needs to be fresh at all times. Probably best used with functions |
preferLayoutEffect | boolean | Should the value be updated using a layout effect or a passive effect. Defaults to false. |
Returnsβ
Return value | Type | Description | Default value |
---|---|---|---|
ref | RefObject | A ref containing the fresh value | () => null |
Codesandbox Examplesβ
Basic Usageβ
Join Bhargav's discord serverβ
You can click on the floating discord icon at the bottom right of the screen and talk to us in our server.