@sanity/form-builder
Version:
Sanity form builder
38 lines (36 loc) • 1.22 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useDidUpdate = useDidUpdate;
var _react = require("react");
var _shallowEquals = _interopRequireDefault(require("shallow-equals"));
var _usePrevious = require("./usePrevious");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* A hook for doing side effects as a response to a change in a hook value between renders
* Usage:
* ```js
* useDidUpdate(hasFocus, (hadFocus, hasFocus) => {
* if (hasFocus) {
* scrollIntoView(elementRef.current)
* }
* })
* ```
* @param current The value you want to respond to changes in
* @param didUpdate Callback to run when the value changes
*/
function useDidUpdate(current, didUpdate) {
var compare = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _shallowEquals.default;
var previous = (0, _usePrevious.usePrevious)(current);
var initial = (0, _react.useRef)(true);
(0, _react.useEffect)(() => {
if (initial.current) {
initial.current = false;
return;
}
if (!compare(previous, current)) {
didUpdate(previous, current);
}
}, [didUpdate, current, previous, compare]);
}