Skip to content

Commit

Permalink
Merge pull request chakra-ui#5445 from rjokelai/fix/useConst-init-fn-…
Browse files Browse the repository at this point in the history
…type

fix: useConst ts issue
  • Loading branch information
segunadebayo authored Jan 25, 2022
2 parents 6f63e44 + 6e259a1 commit 6e65135
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/little-melons-sell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@chakra-ui/hooks": patch
---

fix useConst types when using init function
6 changes: 4 additions & 2 deletions packages/hooks/src/use-const.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
import { useRef } from "react"

type InitFn<T> = () => T

/**
* Creates a constant value over the lifecycle of a component.
*
* Even if `useMemo` is provided an empty array as its final argument, it doesn't offer
* a guarantee that it won't re-run for performance reasons later on. By using `useConst`
* you can ensure that initializers don't execute twice or more.
*/
export function useConst<T extends any | (() => any)>(init: T) {
export function useConst<T extends any>(init: T | InitFn<T>): T {
// Use useRef to store the value because it's the least expensive built-in
// hook that works here. We could also use `useState` but that's more
// expensive internally due to reducer handling which we don't need.
const ref = useRef<T | null>(null)

if (ref.current === null) {
ref.current = typeof init === "function" ? init() : init
ref.current = typeof init === "function" ? (init as InitFn<T>)() : init
}

return ref.current as T
Expand Down
33 changes: 33 additions & 0 deletions packages/hooks/tests/use-const.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { renderHook } from "@chakra-ui/test-utils"
import { act } from "react-test-renderer"
import { useConst } from "../src"

type FooType = { foo: string }

test("should return constant value for constant initialization", () => {
const obj: FooType = { foo: "bar" }
const { rerender, result } = renderHook(() => useConst<FooType>(obj))
expect(result.current).toBe(obj)
act(() => rerender())
expect(result.current).toBe(obj)
})

test("should return constant value even if props change", () => {
const obj: FooType = { foo: "bar" }
const obj2: FooType = { foo: "baz" }
const { rerender, result } = renderHook(({ p }) => useConst<FooType>(p), {
initialProps: { p: obj },
})
expect(result.current).toBe(obj)
act(() => rerender({ p: obj2 }))
expect(result.current).toBe(obj)
})

test("should return constant value from init function", () => {
const { rerender, result } = renderHook(() =>
useConst<FooType>(() => ({ foo: "bar" })),
)
const obj: FooType = result.current
act(() => rerender())
expect(result.current).toBe(obj)
})

0 comments on commit 6e65135

Please sign in to comment.