Hooks react typescript
Hem / Teknik & Digitalt / Hooks react typescript
So if TypeScript sees that is the string , it will automatically know that it should be in the first case and that the should be a string. There are also a few bonuses sprinkled in there, like how to type and how to type custom hooks.
This post is meant both as a tutorial that you can read linearly, but also as a reference that you can go back to whenever you have doubts about any of the topics covered.
This is because for TypeScript, is possibly . Explore comprehensive documentation and rich examples.
Developer-Friendly
Simplify development with an intuitive and powerful API. Don't repeat yourself.
Open-Source
Join the vibrant community! With TypeScript, you can add type safety to your hooks, making your code more robust and easier to debug.
Whether you're managing state with , handling side effects with , or optimizing performance with and , hooks are an essential tool in every React developer's toolkit.
Happy coding!
usehooks-ts
React hook library, ready to use, written in Typescript.
Explore the docs
Features
Lightweight
usehooks-ts is a tiny library without any dependencies, ensuring a lean and efficient solution.
Type-Safe
Catch compile-time errors with ease and unlock strong typing benefits.
Tree-Shakable
Eliminating unused code and delivering leaner bundles for lightning-fast load times.
Easy to Use
Get started in no time!
useContext
The hook allows you to access the value of a React context without wrapping your component in a .
Syntax:
Example:
Explanation:
- takes a context object and returns its current value.
- The value is determined by the nearest above the component in the tree.
4.
Let's say that the initial value of is :
In this case, TypeScript will infer that is of type (which means that it's always ). This is something you should be probably doing anyway, regardless of TypeScript:
The condition in this hook acts as a type guard and guarantees that the returned context won't be .
Bonus: how to type custom hooks
Typing custom hooks is basically the same as typing normal functions, there's nothing to be aware of in particular.
It's relatively common to be using generic types when using custom hooks, so be sure to check out my article about generics if you want to learn more about them and their usage in React.
There is one thing that is worth mentioning with respect to typing hooks, because it's a pattern common in React but less so elsewhere.
I'm speaking about the case when the hook is returning tuple values, such as in and the following example:
TypeScipt will widen the return type of to be : an array that can contain either numbers or strings.
By understanding and using these hooks effectively, you can write cleaner, more maintainable, and performant React applications. It allows functional components to manage state.
Syntax:
Example:
Explanation:
- takes an initial state value and returns an array with two elements: the current state and a function to update it.
- In the example, is the state variable, and is the function to update it.
2.
useCallback
The hook is used to memoize functions so that they are only recreated when their dependencies change. It returns the memoized value, which is only recalculated when the dependencies change.
7. useLayoutEffect
The hook is similar to , but it runs synchronously after all DOM mutations.
With the help of discriminated unions!
And they even have a very nice syntax (in my opinion):
The type is saying that it can take any of the three types contained in the discriminated union. Feel free to bookmark this page for easy access later on.
Rely on type inference if you can
Before diving into the meat of the subject, we have to talk a bit about type inference.
In a lot of cases, TypeScript can infer the type of your hooks itself without your help.
The structure of those types is always the same: if is the name of the HTML tag you're using, the corresponding type will be .
For our input, the name of the type will thus be :
Note that we've added a question mark to .
The code is available on GitHub. See for yourself).
Sometimes you might implicitly return things, which won't make TypeScript happy (so you should avoid it).
Usually, this isn't what you want since the first argument will always be a string and the second example always a number (in this example).
This is how to correctly type the example above:
Wrap up
That's it folks!
I hope this article helped you (and will help you in the future) to know how to type hooks in React.
Steve Kinney
React Hooks and TypeScript together enable incredibly powerful patterns, but they also come with unique typing challenges.
I've already spoiled the first one a bit...
How to type
This will be short, as it's pretty simple and I've already shown multiple examples in the previous section.
That's it: you just have to specify the type of the state in the generic.
How to type
is a bit more complex to type than , because it has more moving parts.
There are two things to type: the and the .
Here is a example from my article on it.