If you are learning React and have started hearing about TypeScript everywhere, you may be wondering:
Why should I use TypeScript with React?
I recently started learning React with TypeScript, and one of the first things I noticed is that TypeScript helps make React code more predictable and easier to understand.
In this article, I'll explain some of the basic concepts I have learned so far.
What is TypeScript?
TypeScript is a programming language built on top of JavaScript.
It adds static typing to JavaScript, which means we can define what kind of data our variables, functions, and objects should contain.
For example:
let username: string = "Osama";
let age: number = 22;
let isStudent: boolean = true;
If we try to assign a number to username:
username = 100;
TypeScript will warn us because username was defined as a string.
This can help us catch many mistakes while writing code instead of discovering them later at runtime.
Why Use TypeScript with React?
React applications often contain a lot of data moving between components.
For example:
Props
State
Event handlers
API responses
Forms
Context
Reducers
TypeScript allows us to describe the shape of this data.
This becomes especially useful as an application grows.
Typing React Props
One of the first things I learned was how to type component props.
Suppose we have a component that receives a user's name and age:
type UserProps = {
name: string;
age: number;
};
const User = ({ name, age }: UserProps) => {
return (
{name}
Age: {age}
);
};
Now TypeScript knows exactly what this component expects.
We can use it like this:
But if we accidentally write:
TypeScript will show errors because the values don't match the types we defined.
What is children?
React components can also receive something called children.
For example:
type CardProps = {
children: React.ReactNode;
};
const Card = ({ children }: CardProps) => {
return
};
Now we can write:
Hello
This content is inside the Card.
The content between and becomes the component's children.
React.ReactNode is commonly used when we want a component to accept different types of React content, such as text, elements, or other components.
Typing State with useState
TypeScript can also help us with React state.
For example:
const [count, setCount] = useState(0);
Here we are telling TypeScript that count should be a number.
We can then do:
setCount(count + 1);
But something like this would cause a type error:
setCount("Hello");
In many simple cases, TypeScript can infer the type automatically:
const [count, setCount] = useState(0);
TypeScript understands that count is a number.
Typing Events
React event handlers are another area where TypeScript is very useful.
For example, with an input:
type InputProps = {
value: string;
handleChange: (
event: React.ChangeEvent
) => void;
};
Now TypeScript knows that handleChange receives a React change event from an HTML input.
We can use it like this:
const Input = ({ value, handleChange }: InputProps) => {
return (
value={value}
onChange={handleChange}
/>
);
};
This gives us better autocomplete and helps prevent mistakes when working with events.
TypeScript and useReducer
TypeScript becomes particularly useful when working with useReducer.
For example, we can define the possible actions:
type UpdateAction = {
type: "increment" | "decrement";
payload: number;
};
type ResetAction = {
type: "reset";
};
type CounterAction = UpdateAction | ResetAction;
Now our reducer knows which actions are allowed.
const reducer = (
state: CounterState,
action: CounterAction
) => {
switch (action.type) {
case "increment":
return {
count: state.count + action.payload,
};
case "decrement":
return {
count: state.count - action.payload,
};
case "reset":
return {
count: 0,
};
default:
return state;
}
};
This is one of the areas where I started to see why TypeScript is useful with React.
Instead of passing arbitrary strings and values around, we can clearly define which actions are valid.
TypeScript Doesn't Replace Understanding React
One important thing I have learned is that TypeScript does not replace understanding React.
You still need to understand:
Components
Props
State
Events
Hooks
Rendering
Component composition
TypeScript simply adds a type system that helps us describe and validate the data used by our React application.
For me, the best approach is to learn React concepts first and then understand how TypeScript describes those concepts.
Final Thoughts
Using TypeScript with React can feel a little difficult at first.
There are new concepts such as:
Types
Interfaces
Union types
Generics
Type inference
React.ReactNode
Event types
But once you understand the basics, TypeScript starts to make React code easier to reason about.
I'm still learning React and TypeScript, and one of the things I like most about this combination is that the code becomes more explicit about what data a component expects and what it can return.
There is still a lot for me to learn, but learning TypeScript alongside React has already changed the way I think about writing React applications.
If you're also learning React with TypeScript, don't try to memorize everything at once. Learn one concept, use it in a small component, and gradually build from there.
Top comments (0)