Skip to content

📣 RFC: Alternative renderHook APIs #56

Open
@mpeyper

Description

@mpeyper

I'm working on the improved docs in #19 and I'm struggling a bit with the section on changing the parameters passed to the hooks. Essentially, my issue is that there are 2 ways you can do it.

The first way is to just keep local variables and update them before rerendering:

let someValue = 0
const { result, rerender } = renderHook(() => useSomeHook(someValue))

// update value
someValue = 1
rerender()

The second way is the use the options.initialProps and rerender(newProps) features:

const { result, rerender } = renderHook(({ someValue }) => useSomeHook(someValue), {
  initialProps: { someValue: 0 }
})

// update value
rerender({ someValue: 1 })

The main reason the second way exists was to work around an issue in our own unit test for ensuring useEffect hooks were testable. The problem was that the updated value was updated for the cleanup of the effect too rather than capturing the initial value. In hindsight, I can see that is probably only an issue for that test, as most users would be passing the values into a hook function, capturing the initial value for the cleanup.

I'm not saying that having the callback function scope the variables isn't still a good idea in some cases, but I think it's a non-issue for most users.

Now we could just remove the initialProps/newProps functionality altogether, but I personally find the usage of a bit more ergonomic, especially when there is more than 1 value to update, as I don't have to keep a variable and spend multiple lines to rerender (1 for each update to the values and the another to render), so I'm asking for opinions on people's preferred API for this.

I'm also open to any ideas for a better API than either of these if you can think of one. I've actually been playing with an idea for a "hook-like" API along the lines of:

const { result, updateProps } = renderHook(() => {
  const someValue = useProps(0)
  return useSomeHook(someValue)
})

// update value
updateProps(1)

Where updateProps calls rerender under the hood. I'm not sure if this is a good idea, just a thought I had. Anyway, let me know your thoughts on any of the above.

Metadata

Metadata

Assignees

No one assigned

    Labels

    request for commentDiscussion about changes to the library

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions