Depending on when you got into programming, more specifically React, your approach will be heavily be influenced by what is available at the time. Somebody that got into programming maybe a decade ago would most definitely be all about monolithic development. Now, if said same person started more recently, they would be more leaning toward microarchitecture. In terms of React, this aligns with favoring React Hooks.

Like with any code, anything of quality must be as predictable as possible. To achieve that predictable behavior we rely on testing. For most coming into hooks, testing can seem quite confusing. It’s normal for an initial reaction to being needed to have a mock component that uses the hook and tests it that way. Very traditional React approach. That is wrong!

Using React Testing Library, you’ll have an already provided testing utility method in renderHook. This method allows for to mock an instance of your hook with the proper props it needs if any, for it to function as well. Let’s look at a light example.

const testHookMock = renderHook(() => {
// You can access the values resulting in this hook 
// by the 'current' prop
// Ex: testHookMock.current

As you can see renderHook is a closure that returns the value you would expect to see in your regular use of your hook. Simple, clean, and provides a great purpose! Now that we’ve had a simple example, we need to take it a bit deeper. Let’s pass on some arguments.

const testHookMock = renderHook(({ state }) => {
}, { initialProps: { state: false } });

Very straightforward, and easy to follow. As you can see you’re defining the arguments your passing into the Function shown as the first argument. From there, you can pass it into the hook you want to test how you see fit.