@primer/react
Version:
An implementation of GitHub's Primer Design System using React
36 lines (35 loc) • 1.32 kB
JavaScript
import { c } from "react-compiler-runtime";
import { useState } from "react";
//#region src/hooks/useSyncedState.tsx
/**
* When the value that initialized the state changes
* this hook will update the state to the new value, immediately.
*
* This uses an Object.is comparison to determine if the value has changed by default
*
* If you use a non-primitive value as the initial value, you should provide a custom isEqual function
*
* This is adapted almost directly from https://beta.reactjs.org/learn/you-might-not-need-an-effect#adjusting-some-state-when-a-prop-changes
*/
const useSyncedState = (initialValue, t0) => {
const $ = c(2);
const { isPropUpdateDisabled: t1, isEqual: t2 } = t0 === void 0 ? {} : t0;
const isPropUpdateDisabled = t1 === void 0 ? false : t1;
const isEqual = t2 === void 0 ? Object.is : t2;
const [state, setState] = useState(initialValue);
const [previous, setPrevious] = useState(initialValue);
const nextInitialValue = initialValue instanceof Function ? initialValue() : initialValue;
if (!isPropUpdateDisabled && !isEqual(previous, nextInitialValue)) {
setPrevious(nextInitialValue);
setState(nextInitialValue);
}
let t3;
if ($[0] !== state) {
t3 = [state, setState];
$[0] = state;
$[1] = t3;
} else t3 = $[1];
return t3;
};
//#endregion
export { useSyncedState };