# How to write and test a custom React hook.

> What's a custom hook? How can we use them, and test them?

Daniel Fernández · Jan 23, 2021 · https://dfrico.com/blog/2021-01-23-testing

useEffect(callback, useDeepCompareMemoize(dependencies));
}

```

## How can we test a custom hook?

The tricky part about testing a custom hook, like in other cases, is that we need to emulate the behavior of a react hook, without rendering the application (as we run the tests from the CLI).

Luckily, [React testing library](https://testing-library.com) has a great set of [testing utilities for React hooks](https://github.com/testing-library/react-hooks-testing-library). One of their use cases is precisely if _"You're writing a library with one or more custom hooks that are not directly tied to a component"_, which fits our utility function.

We can use it to implement a test that mocks a callback function that will be called everytime the dependencies array changes:

```javascript
import { renderHook } from '@testing-library/react-hooks';

it('should trigger callback only on dependencies change', () => {
  // we're creating a fake callback function to check wether or not
  // it's been called.
  const callback = jest.fn();
  // we create a fake array of dependencies.
  let dependencies = [{ a: 1 }];
  // we'll use RTL's renderHook to return a result and a rerender method
  const { result, rerender } = renderHook(() =>
    useDeepCompareEffect(callback, dependencies)
  );

  expect(result).toBeTruthy();
  // dependencies didn't change
  rerender({ callback, dependencies });

  dependencies = [{ a: 2 }];
  // dependencies did change, triggering useEffect
  rerender({ callback, dependencies });

  // we check here that we called our custom fake callback twice so far
  expect(callback).toHaveBeenCalledTimes(2);
});
```

Here is [the code for the utility](https://github.com/Vizzuality/usa-resilience-opportunity-map/blob/testing/utils/deepCompare.js), and this is [the tests file](https://github.com/Vizzuality/usa-resilience-opportunity-map/blob/testing/utils/deepCompare.test.js).

Do you know of a better way to implement and try custom React hooks? Do you have any further questions about this short article? Feel free to reach me [on Twitter](https://twitter.com/blayhem)!

Hope you enjoyed this article, see you on the next one <span role="img" aria-label=":v:">✌🏻</span>
