← Back to blog Post

React custom hooks: design and testing

Hosted here as an English translation. Originally published on Lean Mind.

React is one of the most widely used frontend libraries today, and since version 16.8.0 it has officially included hooks.

What are hooks?

Hooks are functions used by components to extract responsibilities that would otherwise remain embedded inside the component itself. They can only be used by functional components, and by convention they usually start with the use prefix.

React provides built-in hooks such as useState, useEffect, and useContext, but we can also create our own hooks to encapsulate reusable logic.

How are they used?

A common example is wrapping the logic for loading a profile from an API. Instead of repeating loading, profile, and error handling across several components, we can extract it into a hook such as useProfile(repository).

That hook can return:

  • the loading state,
  • the retrieved profile,
  • the possible error,
  • and a function such as getProfile to trigger the action.

That way, the component becomes simpler and focuses on rendering state rather than hosting all the internal logic.

Testing

Is it necessary to test a hook? It depends. If the feature is already fully covered through the component tests, maybe not. But when a hook contains relevant behavior or is developed more independently, isolated tests can be very valuable.

One useful option is @testing-library/react-hooks, which lets us mount the hook, execute actions, and inspect how state evolves.

The basic approach is:

  1. mock the repository,
  2. mount the hook with renderHook,
  3. run the action inside act,
  4. and assert the final state.

Conclusion

Custom hooks help reduce fear around extracting logic from components and make code more reusable and easier to test. They also create a cleaner path toward more advanced sharing strategies such as lifting state up or exposing it through context.

  • react
  • hooks
  • testing