diff options
Diffstat (limited to 'examples/with-changesets/packages/acme-utils/src')
4 files changed, 51 insertions, 0 deletions
diff --git a/examples/with-changesets/packages/acme-utils/src/index.tsx b/examples/with-changesets/packages/acme-utils/src/index.tsx new file mode 100644 index 0000000..6098c1f --- /dev/null +++ b/examples/with-changesets/packages/acme-utils/src/index.tsx @@ -0,0 +1,3 @@ +export { toSlug } from "./toSlug"; +export { useIsomorphicLayoutEffect } from "./useIsomorphicLayoutEffect"; +export { usePrevious } from "./usePrevious"; diff --git a/examples/with-changesets/packages/acme-utils/src/toSlug.ts b/examples/with-changesets/packages/acme-utils/src/toSlug.ts new file mode 100644 index 0000000..6aec61c --- /dev/null +++ b/examples/with-changesets/packages/acme-utils/src/toSlug.ts @@ -0,0 +1,18 @@ +/** + * Return a slugified copy of a string. + * + * @param {string} str The string to be slugified + * @return {string} The slugified string. + */ +export function toSlug(str: string): string { + let s = str; + if (!s) { + return ""; + } + s = s.toLowerCase().trim(); + s = s.replace(/ & /g, " and "); + s = s.replace(/[ ]+/g, "-"); + s = s.replace(/[-]+/g, "-"); + s = s.replace(/[^a-z0-9-]+/g, ""); + return s; +} diff --git a/examples/with-changesets/packages/acme-utils/src/useIsomorphicLayoutEffect.tsx b/examples/with-changesets/packages/acme-utils/src/useIsomorphicLayoutEffect.tsx new file mode 100644 index 0000000..59a7899 --- /dev/null +++ b/examples/with-changesets/packages/acme-utils/src/useIsomorphicLayoutEffect.tsx @@ -0,0 +1,13 @@ +import * as React from "react"; + +/** + * On the server, React emits a warning when calling `useLayoutEffect`. + * This is because neither `useLayoutEffect` nor `useEffect` run on the server. + * We use this safe version which suppresses the warning by replacing it with a noop on the server. + * + * See: https://reactjs.org/docs/hooks-reference.html#uselayouteffect + */ +const useIsomorphicLayoutEffect = + typeof window !== "undefined" ? React.useLayoutEffect : () => {}; + +export { useIsomorphicLayoutEffect }; diff --git a/examples/with-changesets/packages/acme-utils/src/usePrevious.tsx b/examples/with-changesets/packages/acme-utils/src/usePrevious.tsx new file mode 100644 index 0000000..8024464 --- /dev/null +++ b/examples/with-changesets/packages/acme-utils/src/usePrevious.tsx @@ -0,0 +1,17 @@ +import * as React from "react"; + +function usePrevious<T>(value: T) { + // The ref object is a generic container whose current property is mutable ... + // ... and can hold any value, similar to an instance property on a class + const ref = React.useRef<T>(value); + + // Store current value in ref + React.useEffect(() => { + ref.current = value; + }, [value]); // Only re-run if value changes + + // Return previous value (happens before update in useEffect above) + return ref.current; +} + +export { usePrevious }; |
