7 TypeScript Patterns You Should Be Using

Spanish audio is available in the player settings
Rate this content
Bookmark

In this talk, we will be going over a number of common useful and best-practice-proven TypeScript patterns to use in React 18. This includes how to correctly type component properties, children and return types, using React's built-in types, typing contexts, and the usual enum rant (but constructively).

Morten Barklund
Morten Barklund
19 min
06 Jun, 2023

Video Summary and Transcription

This Talk introduces 7 essential TypeScript patterns for React development, including children, spreading props, either-or, generic components, and context. The speaker demonstrates various implementations and provides examples using a fictional dog grooming salon application. Other interesting ideas include using omit and make required types, creating components with either-or interfaces, and using generics, memorization, and context in React. The speaker also introduces the Recontextual library for context management.

Available in Español

1. Introduction to TypeScript Patterns in React

Short description:

Did you know that despite the fact that around 80% of React developers are using TypeScript, most of the courses, books, and supporting materials for learning React are almost exclusively in JavaScript? Today, I'm here to share with you 7 essential TypeScript patterns that you can start using right away to make your React development safer, more efficient, and more enjoyable than ever before. My name is Morten and I'm a React and TypeScript enthusiast. I'm the author of 2 books on React. Follow me on LinkedIn and subscribe to my newsletter at mortenbaklund.com for more tips and tricks.

Did you know that despite the fact that around 80% of React developers are using TypeScript, most of the courses, books, and supporting materials for learning React are almost exclusively in JavaScript? This has left many developers struggling to navigate the complex role of TypeScript in React development.

Today, I'm here to change all that. I want to share with you 7 essential TypeScript patterns that you can start using right away to make your React development safer, more efficient, and more enjoyable than ever before. My name is Morten and I really like dogs. I'm here as both a React and TypeScript enthusiast. I'm the author of 2 books on React. First React Quickly, a primer on React fundamentals. It's at the printers pretty much right now and will be out in print this month. Secondly, Job Ready React. It builds on the first book. It covers the React ecosystems and more complex React patterns. It's in the works, about 80% done, will be out in the fall sometime. You can get the books from the two links above or just by Googling the titles really. Besides that, I also run workshops and I'm working on a new course platform that I think will be quite innovative. You can read about that at codingheaven.deb. Finally, follow me on LinkedIn and please do subscribe to my newsletter at mortenbaklund.com for lots more tips and tricks.

2. Introduction to React Component Patterns

Short description:

In this part, we'll cover seven essential TypeScript patterns for React development. These patterns include children, spreading props, either-or, generic components, and context. We'll explore different variations and implementations, even sacrificing proper React coding to illustrate key points. Additionally, we'll work with an application called Waxville, a fictional dog grooming salon, to demonstrate the patterns. The application is available on GitHub and waxville.org, but please note that it only stores data in memory and is solely for illustrative purposes.

All right, back to the topic. The title here is a bit hyperbolic. These patterns tend to blend a bit into each other, but the overall plan is as follows. We'll introduce what we want to achieve by looking at the final application. Then we'll look at the API from the parent component perspective and then we'll see how we can implement that inside a component. We'll probably look at a few different variations and see which one is the best one.

The examples are not always great code design because some of these examples have been reduced a bit in complexity to make them simple and instructive. The patterns are still fully valid, but they only appear in more complex code. So I've sometimes sacrificed proper React coding a bit to illustrate some points.

These are the seven patterns we'll cover. Children, spreading props, either-or, generic components, and context. You might now be thinking, wait, was that seven or was that only five? So let's expand the list a bit because we can do this in a few different ways. So either-or, we can do that with unions or discriminated unions. Those are slightly different patterns that are definitely both valid. And for context, there's two different situations that have definitely different complexity. We have simple context and we have selectable context. Those are very different, and we'll see how we can implement both of them.

In this talk, I'll be working on an application called Waxville. It's a fictional dog grooming salon that I've created just for this talk. You can see the repo here on GitHub, and you can see the website live at waxville.org. You can go see that right now. This is just a quick demo that you can see that you can log in. It doesn't actually matter what you type. When you press the button, you log in, and then there's a schedule with the daily appointments, and there's a CRUD interface for employees, customers, and services. Be aware, this is a very dumb website. It only stores the data in memory. So once you reload the website, everything you've done is gone. So this is to not make sure that anyone messes with it, but also it's enough to illustrate all the points we're going to make. This is not about data APIs. This is just about typing components.

3. Children Pattern in React

Short description:

The first pattern we'll discuss is children. It's a special property that needs to be typed correctly to allow different types of child content. We can use the props with children interface from the react package to ensure correct typing. This approach is more transparent and eliminates the need for custom interfaces when there are no additional props. We can also easily handle other properties by creating an interface for non-children props.

So the first pattern we're going to discuss is children. Children is a special property that you probably all know, and has to be typed correctly to allow the node to contain all the different possible types of child content. An example would be our auth provider that we have at the root of our application. We can type this using a custom interface, and we just type the children property as react-node from the react package. This type includes all the correct possibilities, including string, numbers, Booleans, elements, lists, etc.

However, I think a better and more transparent approach is to use the props with children interface from the react package instead. We don't need to have our own interface at all when we don't have any props. We just use this interface as is. It makes it more clear that we've correctly typed this children property. If our component takes other properties, we can easily deal with that too. Here we have the menu with menu items. A menu item takes a child attribute, but also takes a to property, which is the page it links to. We can implement that with Props with Children, where we just create an interface for the non-children properties, and we pass that as a type argument. This looks really nice.

4. Spreading Props in React

Short description:

Next, let's discuss spreading props, also known as mirroring the props of another component. We can achieve this by specifying an interface that mirrors all the properties of a normal button while extending it with custom ones. There are different approaches for achieving this, such as using the button.html.attributes interface or going through the JSX namespace. However, both approaches have drawbacks, such as awkward typing or including the ref property. To overcome these issues, I prefer using components without ref, which can be extended and does not include ref. This approach allows us to extract props for any component, including custom ones.

Next up, spreading props. This is also sometimes referred to as mirroring the props of another component. A very simple example here is a button. In the Custom Edit form, we have two buttons at the bottom, cancel and save. They're slightly different, but they're implemented with the same component. We can see them here in the Edit form, where the buttons take some default properties that normal buttons do, like type, onClick, and children, but also some custom ones, like outline and icon.

What we want to achieve is to specify an interface that mirrors all the properties of a normal button, but extends it with a few custom ones. One fairly obvious way is to use the button.html.attributes interface from React like this. It however has the drawback of requiring an additional interface for the event handler targets, where we need HTMLButtonElement from the DOM. It's a bit awkward to type button.html and then HTMLButton, but it works and is fully functional. Because of the awkwardness, it's not that used, this approach.

A more common choice is to go through the JSX namespace and access the intrinsic elements property. It addresses all the types for all the intrinsic elements. This has another weird drawback though. You cannot directly extend it. If you try to extend this with an interface, you get a weird TypeScript parsing error. The TypeScript grammar simply doesn't allow extending a bracket index interface like this. We can save it in a type and extend that. But we have to go through that extra type. Both of the above also have an additional drawback though. They both include ref because that's a valid property that you can pass to a component, but it's never a valid property to receive inside a component in the props object. So this would be valid TypeScript, but it doesn't really make any sense. That's not how we receive a ref. For those reasons, I prefer to use components without ref.

Component props without ref. It requires a specific element name as a type argument. And it can be extended just fine and it does not include ref. Which is pretty obvious from the name of it. This interface can actually be used to extract props of any component, including custom ones, but I use it mostly for intrinsic HTML elements. Sometimes we don't want to allow the same elements of the same properties for a built-in element.

5. TypeScript Patterns: Omit and Make Required

Short description:

To achieve a nice display model for a number input, we use the omit-typescript type and change the type of the value property. We can narrow the type without omitting it from the parent interface. For the Form component, we use the Make Required utility type to remove the optional part of the type and ensure the unsubmit function is required.

For example, for this number input that you can see in action here. It has a nice display model where the number is formatted differently on blur. To do this, we can't allow users of the component to specify type or pattern as that would circumvent the purpose. We implement this using the omit-typescript type. Further trick here is that we actually change the type of the value property. On a regular input element, value is an optional property that allows numbers, strings and undefined. But on our component, it's a required property that only allows numbers. We can do that without using omit. We don't have to omit it from the parent interface because we're narrowing the type. If you want us to change the type to something that was not included in the original, for example, a function, we'd have to omit it from the original before changing it. Narrowing is allowed when extending, but not changing. We also use this same idea to only remove the optional part of a type. For example, in our Form component, we want to require the unsubmit function. We cannot have that as optional. We want to make sure that everyone who uses this component always supply an unsubmit function. But the type of this one is a bit complex. We can use the original type, but then we have to index the original in this quite weird way. It's a bit repetitive, especially if we had more than one property we wanted to do in this way. A better way is to create a small utility type called Make Required, where we can use a type modifier to remove the optional part of the type by using this minus question mark syntax. It makes for a much cleaner interface and we now only have to specify the new types that are not on the original.

6. Components with Either-or Interfaces

Short description:

Next, we'll create components that require attributes to conform to either a link action or a click action. We'll use TypeScript's narrowing to determine the type of action based on the properties present in the value. Additionally, we'll explore discriminated unions and how they can be used to create components that can be either single select or multi-select, with corresponding callbacks that accept either single elements or arrays of elements. We'll also discuss the benefits of using union string types instead of enums for cases with more than two choices.

Next up we'll create components that require attributes to conform to exactly one of several interfaces in an either-or situation. In our table example, we have an ability to add action buttons as you can see here. These two buttons are slightly different though. One of them is a link, the other is a button with a callback. In the serviceList component, we can see here that we specify an action label always, but we either specify a link property or an onClick callback, but we cannot specify both, that would be invalid. We want to make sure to type this correctly inside the table implementation.

Here we see that action is a union type of link action or click action and our table then accepts an optional list of actions. Using this inside the component is a bit complex though. We have to utilize TypeScript's narrowing and the cleanest way to do that is to check if a given property exists in the value. If the action object contains a link property, then it's probably a link action, and even TypeScript knows that, so it knows the properties. If it doesn't contain a link property, it must be a click action, so it contains an onClick function, and TypeScript knows that as well. But the property check is a bit ugly. We can move it to a type guard and we do the same thing, and it looks better, but it's still a bit complex. What if we instead had a property on the different interfaces in the union that could directly discriminate between which specific union member we were working with? Well, that's a discriminated union.

We have another example here in our Select component. Our Select component can either be a single select or a multi-select, as you can see here, two different selects in the same form. The difference is that the value for a single select is a single element, but for multi-select it's an array of elements. And for the callback, we can also either get a single element back or we get multiple elements back in the callback. You can see here how if we add a manual callback to these two components it knows directly if it received a single string or if it receives a list of strings. We can implement that with two interfaces that share a property that directly tells us which case we have. That's of course the multiple property. We can directly use that property inside the implementation to correctly invoke the callback with the proper arguments. And TypeScript correctly knows that the callback accepts these correct arguments. In this example we only had two choices, so it could be done with a Boolean. If you have more than two, the easiest way is to implement this with a union string type. You don't need an enum. There's nothing an enum could give you that a union string type couldn't do just as well. You would only just create unnecessary code, which enums do. So stick with a union string type and you'll be good. However this select, it only accepted strings and then returned strings back.

7. Generics, Memorization, and Context in React

Short description:

To put in an arbitrary element and receive it back in a callback, we use generics. The table displays different columns in different lists, implemented with a generic type. However, when memorizing components, the specific type of argument is lost. We can fix this by changing the type of the memorized component or the global type for the memo function. Context is a more complex topic, where we use React's built-in context to serve our auth provider in the login component.

What if we wanted to put in an arbitrary element and receive that same element back in a callback? To do that we need to use generics. Let's take a closer look at our table from before. We can see the table displays different columns in the different lists. We do that with a generic type. You can also see here that in the on click callback for an action it knows exactly which properties exist on the particular element and this directly maps back to the input rows for that same table. This is implemented with a generic type.

We restrict the generic type to extend a record with an ID and we otherwise just use the generic type as we'd use any specific type. There's one small caveat to this in React though. If we memorise the component and go back to where we used the link action, it suddenly forgot what specific type of argument it received. Memorise simply removes any generic types. So this now is only typed as a record with an ID. It doesn't know about any of the other properties. That's how a memo function is typed in React. I think it's a bit broken and it should be fixed. But for now we can fix that in one of two ways. If this is just a one-off component we have, we can fix it by simply changing the type of the memorised component to be the same as the type of the component. It's very simple. If we have to do this at scale for multiple components, we can instead change the global type for the memo function inside React. Yes, we can do that. We just specify that the memo just returns whatever it receives. ForwardRef has the exact same issue. And that might also come up in your code. And it's a bit trickier to type correctly, but you can still do that in both ways.

Let's move on to a more complex topic. Context. First we have a simple context. It's our auth provider. We'll use React's built-in context to serve it. It is used in the login component. So when we press the login button, we invoke the login function from the context.

8. Creating Context in React

Short description:

When creating a context in React, allowing the context to be null can make the process easier. However, passing null as the value in the provider can break the consumers. If null is not allowed, creating the context becomes more complex. Typing out the context with multiple properties can be tedious.

And that changes some flag somewhere saying that we are now logged in. In the root component, we send the user to a different page depending on the logged in status. In the login component, we invoke login from this context and that is done on form submission. We create this context with an interface and the built-in create context. Here we additionally allow the context to be null. Just to be able to pass a null into create context. This makes it a lot easier to create the context. We have a custom hook for accessing the context which fills out null. So we know that's not going to happen and it always just returns the context value. In the auth provider, we pass in a value with a proper structure. But as you can see here, we could actually pass in null for the value in the provider. It will break the consumers as we throw on null, but the type system actually allows it. If we did not allow null, we will have to create the compact context in a more complex manner for no real purpose. Here we only have two properties, but if we had more properties, it would be a really long, really annoying contexts to type out.

9. Using Selectable Context and Recontextual Library

Short description:

Sometimes people use partial instead, but it leads to the same problems. A better approach is to use a selectable context. There's a great library called useContextSelector that allows us to do just that. We can now pass a selector function. When we select from our context, we have this overloaded function. It's not pretty. It's a bit complex, but it works. For that very reason, I've created a small library called Recontextual which does exactly this. It wraps useContextSelector and simplifies the API. Let's see how we use that in ScheduleProvider.

Sometimes people use partial instead, but it leads to the same problems. For instance, in the login component, we will have to check if the login function existed before we could invoke it, because it's now an optional property and not a required property.

A simple context like this is not useful at scale. If any property inside the context changes, every consumer re-renders. In our example from before, the login component re-renders when we log in, because it is logged in property of the context changes, even though we don't use that property in the login component at all.

A better approach is to use a selectable context. There's a great library called useContextSelector that allows us to do just that. Let's look at the underlying API provider that handles all the primary data for the CRUD application. This API allows us to edit, add, and delete services, and handles updating the state. But we don't want context consumers that aren't using NGATE services to re-render just because we add a new service.

We can now pass a selector function. In the schedule, we select a single property from the API provider, the employees, so we can display them all. But more often, we actually select multiple properties, and to make sure that caching and re-rendering works, we need to shallowy compare the returned objects, so we also pass in a boolean flag. We'll see how this selector function works in a while, but let's first see how the context is created.

We're actually still allowing null here to make creating the context easier. This context has multiple values, so if we had to type them all out, it would be a lot of work. Allowing null makes that a lot easier and a lot more compact. This is because this library.useContextSelector is still required as an initial value for the context. In the provider, we apply the value in the same way as normal, and you can also see here this still allows null to be passed in. But now things get complex. When we select from our context, we have this overloaded function. It allows us to either select the whole context if we pass in nothing, select a single value if we pass in a selector, or select multiple value if we pass in a selector and true. It's not pretty. It's a bit complex, but it works. But if you need this for multiple contexts throughout your application, it's very repetitive to copy around. For that very reason, I've created a small library called Recontextual which does exactly this. It wraps useContextSelector and simplifies the API. It is slightly opinionated about what the API should look like, but I think this is still very generic and can be used for most people. It does not allow a default value, but I also don't think that people use the default value of more complex contexts anyway. Let's see how we use that in ScheduleProvider.

10. Using Recontextual Library for Context Management

Short description:

We display the daily schedule and a small calendar component. The calendar component selects multiple values from the context, while the schedule selects a single value. The implementation is in a file called Recontextual.ts. The library, located on GitHub, has a small footprint. If you have any feedback, please message me on LinkedIn. Thank you for listening!

You can see it in action here. We display the daily schedule in the bottom, and in the top we can change the day and also display which day is the current day in a small calendar component.

So in the calendar component here, we select multiple values from the context, and in the schedule, we select just a single value. This is implemented here in a file called Recontextual.ts. It just requires the context type, and that's it. It returns a provider and selector function, and everything is taken care of.

In the provider, we pass in a value, and as you can see here, null is actually not allowed. It does use null internally, but it doesn't expose the fact that it uses null. So it's not allowed. We have to pass in a proper value. The library is located here in GitHub, and it has a very small footprint. I really hope that you like it and you would want to play around with it.

Those are all my tips. I'll be around for Q&A right after this talk. If you think I made a boo-boo or anything weird, or you think I'm just wrong, please throw me a message on LinkedIn. That's probably the best place to reach me. Thank you so much for listening, and please consider buying my books.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

A Guide to React Rendering Behavior
React Advanced Conference 2022React Advanced Conference 2022
25 min
A Guide to React Rendering Behavior
Top Content
React is a library for "rendering" UI from components, but many users find themselves confused about how React rendering actually works. What do terms like "rendering", "reconciliation", "Fibers", and "committing" actually mean? When do renders happen? How does Context affect rendering, and how do libraries like Redux cause updates? In this talk, we'll clear up the confusion and provide a solid foundation for understanding when, why, and how React renders. We'll look at: - What "rendering" actually is - How React queues renders and the standard rendering behavior - How keys and component types are used in rendering - Techniques for optimizing render performance - How context usage affects rendering behavior| - How external libraries tie into React rendering
Building Better Websites with Remix
React Summit Remote Edition 2021React Summit Remote Edition 2021
33 min
Building Better Websites with Remix
Top Content
Remix is a new web framework from the creators of React Router that helps you build better, faster websites through a solid understanding of web fundamentals. Remix takes care of the heavy lifting like server rendering, code splitting, prefetching, and navigation and leaves you with the fun part: building something awesome!
React Compiler - Understanding Idiomatic React (React Forget)
React Advanced Conference 2023React Advanced Conference 2023
33 min
React Compiler - Understanding Idiomatic React (React Forget)
Top Content
React provides a contract to developers- uphold certain rules, and React can efficiently and correctly update the UI. In this talk we'll explore these rules in depth, understanding the reasoning behind them and how they unlock new directions such as automatic memoization. 
Using useEffect Effectively
React Advanced Conference 2022React Advanced Conference 2022
30 min
Using useEffect Effectively
Top Content
Can useEffect affect your codebase negatively? From fetching data to fighting with imperative APIs, side effects are one of the biggest sources of frustration in web app development. And let’s be honest, putting everything in useEffect hooks doesn’t help much. In this talk, we'll demystify the useEffect hook and get a better understanding of when (and when not) to use it, as well as discover how declarative effects can make effect management more maintainable in even the most complex React apps.
Routing in React 18 and Beyond
React Summit 2022React Summit 2022
20 min
Routing in React 18 and Beyond
Top Content
Concurrent React and Server Components are changing the way we think about routing, rendering, and fetching in web applications. Next.js recently shared part of its vision to help developers adopt these new React features and take advantage of the benefits they unlock.In this talk, we’ll explore the past, present and future of routing in front-end applications and discuss how new features in React and Next.js can help us architect more performant and feature-rich applications.
(Easier) Interactive Data Visualization in React
React Advanced Conference 2021React Advanced Conference 2021
27 min
(Easier) Interactive Data Visualization in React
Top Content
If you’re building a dashboard, analytics platform, or any web app where you need to give your users insight into their data, you need beautiful, custom, interactive data visualizations in your React app. But building visualizations hand with a low-level library like D3 can be a huge headache, involving lots of wheel-reinventing. In this talk, we’ll see how data viz development can get so much easier thanks to tools like Plot, a high-level dataviz library for quick & easy charting, and Observable, a reactive dataviz prototyping environment, both from the creator of D3. Through live coding examples we’ll explore how React refs let us delegate DOM manipulation for our data visualizations, and how Observable’s embedding functionality lets us easily repurpose community-built visualizations for our own data & use cases. By the end of this talk we’ll know how to get a beautiful, customized, interactive data visualization into our apps with a fraction of the time & effort!

Workshops on related topic

React Performance Debugging Masterclass
React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured WorkshopFree
Ivan Akulov
Ivan Akulov
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
Concurrent Rendering Adventures in React 18
React Advanced Conference 2021React Advanced Conference 2021
132 min
Concurrent Rendering Adventures in React 18
Top Content
Featured WorkshopFree
Maurice de Beijer
Maurice de Beijer
With the release of React 18 we finally get the long awaited concurrent rendering. But how is that going to affect your application? What are the benefits of concurrent rendering in React? What do you need to do to switch to concurrent rendering when you upgrade to React 18? And what if you don’t want or can’t use concurrent rendering yet?

There are some behavior changes you need to be aware of! In this workshop we will cover all of those subjects and more.

Join me with your laptop in this interactive workshop. You will see how easy it is to switch to concurrent rendering in your React application. You will learn all about concurrent rendering, SuspenseList, the startTransition API and more.
React Hooks Tips Only the Pros Know
React Summit Remote Edition 2021React Summit Remote Edition 2021
177 min
React Hooks Tips Only the Pros Know
Top Content
Featured Workshop
Maurice de Beijer
Maurice de Beijer
The addition of the hooks API to React was quite a major change. Before hooks most components had to be class based. Now, with hooks, these are often much simpler functional components. Hooks can be really simple to use. Almost deceptively simple. Because there are still plenty of ways you can mess up with hooks. And it often turns out there are many ways where you can improve your components a better understanding of how each React hook can be used.You will learn all about the pros and cons of the various hooks. You will learn when to use useState() versus useReducer(). We will look at using useContext() efficiently. You will see when to use useLayoutEffect() and when useEffect() is better.
React, TypeScript, and TDD
React Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
Paul Everitt
Paul Everitt
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
Web3 Workshop - Building Your First Dapp
React Advanced Conference 2021React Advanced Conference 2021
145 min
Web3 Workshop - Building Your First Dapp
Top Content
Featured WorkshopFree
Nader Dabit
Nader Dabit
In this workshop, you'll learn how to build your first full stack dapp on the Ethereum blockchain, reading and writing data to the network, and connecting a front end application to the contract you've deployed. By the end of the workshop, you'll understand how to set up a full stack development environment, run a local node, and interact with any smart contract using React, HardHat, and Ethers.js.
Designing Effective Tests With React Testing Library
React Summit 2023React Summit 2023
151 min
Designing Effective Tests With React Testing Library
Top Content
Featured Workshop
Josh Justice
Josh Justice
React Testing Library is a great framework for React component tests because there are a lot of questions it answers for you, so you don’t need to worry about those questions. But that doesn’t mean testing is easy. There are still a lot of questions you have to figure out for yourself: How many component tests should you write vs end-to-end tests or lower-level unit tests? How can you test a certain line of code that is tricky to test? And what in the world are you supposed to do about that persistent act() warning?
In this three-hour workshop we’ll introduce React Testing Library along with a mental model for how to think about designing your component tests. This mental model will help you see how to test each bit of logic, whether or not to mock dependencies, and will help improve the design of your components. You’ll walk away with the tools, techniques, and principles you need to implement low-cost, high-value component tests.
Table of contents- The different kinds of React application tests, and where component tests fit in- A mental model for thinking about the inputs and outputs of the components you test- Options for selecting DOM elements to verify and interact with them- The value of mocks and why they shouldn’t be avoided- The challenges with asynchrony in RTL tests and how to handle them
Prerequisites- Familiarity with building applications with React- Basic experience writing automated tests with Jest or another unit testing framework- You do not need any experience with React Testing Library- Machine setup: Node LTS, Yarn