UNPKG

react-use-latest-state

Version:

A lightweight React package that enhances the reliability of state values within functional components. By utilizing useRef under the hood, useLatestState ensures that you always access the latest state value, eliminating common pitfalls when working with

46 lines 1.52 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useLatestState = void 0; const react_1 = require("react"); const useLatestState = function (initialValue) { // Use a reference to store the latest // value of the state. const valueRef = (0, react_1.useRef)(initialValue); const [value, setValue] = (0, react_1.useState)(initialValue); // Whenever the value of state changes, // automatically store the latest value // inside `valueRef`. (0, react_1.useEffect)(() => { valueRef.current = value; }, [value]); /** * @returns {T} Latest state value */ function getValue() { return valueRef.current; } /** * @param {React.SetStateAction<T>} value * @returns {void} */ function customSetValue(value) { // If the `value` is a function, // call the function by passing latest // state value, and obtain the updated // state value. if (typeof value === "function") { const updatedValue = value(valueRef.current); valueRef.current = updatedValue; setValue(updatedValue); return; } // If the `value` is supplied // directly, simply update the state // and store the value in the reference. valueRef.current = value; setValue(value); } return [getValue, customSetValue]; }; exports.useLatestState = useLatestState; //# sourceMappingURL=useLatestState.js.map