UNPKG

rooks

Version:

Essential React custom hooks ⚓ to super charge your components!

43 lines (42 loc) 1.65 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useDidUpdate = void 0; var react_1 = require("react"); var useDidMount_1 = require("./useDidMount"); var useWillUnmount_1 = require("./useWillUnmount"); /** * useDidUpdate hook * * Fires a callback on component update * Can take in a list of conditions to fire callback when one of the * conditions changes * * @param {Function} callback The callback to be called on update * @param {Array} conditions The list of variables which trigger update when they are changed * @see https://react-hooks.org/docs/useDidUpdate */ function useDidUpdate(callback, conditions) { var hasMountedRef = (0, react_1.useRef)(false); var internalConditions = (0, react_1.useMemo)(function () { if (typeof conditions !== "undefined" && !Array.isArray(conditions)) { return [conditions]; } else if (Array.isArray(conditions) && conditions.length === 0) { console.warn("Using [] as the second argument makes useDidUpdate a noop. The second argument should either be `undefined` or an array of length greater than 0."); } return conditions; }, [conditions]); (0, react_1.useEffect)(function () { if (hasMountedRef.current) { callback(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, internalConditions); (0, useDidMount_1.useDidMount)(function () { hasMountedRef.current = true; }); (0, useWillUnmount_1.useWillUnmount)(function () { hasMountedRef.current = false; }); } exports.useDidUpdate = useDidUpdate;