Education
Last updated on Sep 5, 2024
Last updated on Apr 21, 2023
Recently, there has been an increasing trend toward using React function components for building user interfaces.
In this post, we will break down everything you need to know about the React Function components.
Why are they preferred over class components?
The Advanced TypeScript Techniques for React Function Components.
And the Importance of using TypeScript with React Function Components.
So, let’s dive in.
These are a type of component in the React JavaScript library that allow developers to create reusable pieces of code to build user interfaces. They are defined as plain JavaScript functions that return a React element or JSX (a syntax extension for JavaScript that allows for HTML-like code within JavaScript).
The React Function Components are typically used for simpler UI components and are favored due to the following reasons:
Moreover, with the introduction of React Hooks, function components have become even more powerful, allowing developers to use state and other React features without writing a class.
In React, there are two types of components that can be used to build the user interface:
While both types of components can achieve the same result, function components have become increasingly popular for a number of reasons.
Simplicity: Function components are simpler and easier to understand than class components. They are less verbose and have a lower cognitive load, making them easier to read and maintain. This simplicity also makes them easier to write and debug.
Performance: Function components are faster and more efficient than class components. They do not have the overhead of a class instance, which can lead to better performance in certain scenarios.
Hooks: Function components can leverage the power of React Hooks. Hooks are a new addition to React that allows you to use state and other React features without writing a class. They are more flexible and reusable than class components.
Functional Programming: Function components promote functional programming practices, which can lead to cleaner and more maintainable code. By focusing on pure functions, function components can be more predictable and easier to test.
Future-Proofing: Function components are the future of React. React has been moving towards function components since the introduction of Hooks. While class components will still work in React, function components are likely to be the standard going forward.
React is the most popular JavaScript library for building user interfaces, and TypeScript is a powerful tool for adding type safety to JavaScript. Together, React and TypeScript can create scalable and maintainable applications.
So, let's explore some advanced TypeScript techniques for React function components to create robust and type-safe components.
Function components in React receive props as their first argument. TypeScript allows you to define the type of the props object. This provides better type safety throughout the component.
1 interface Props { 2 name: string; 3 age: number; 4 } 5 6 const MyComponent: React.FC<Props> = ({ name, age }) => { 7 return ( 8 <div> 9 <h1>{name}</h1> 10 <p>{age}</p> 11 </div> 12 ); 13 }; 14
By defining the type of “Props”, we ensure that the component only receives the correct props. This approach helps to catch errors early and create more robust components.
Default props in React are values that are used if the prop is not explicitly provided. TypeScript can define the type of the default props object.
1 interface Props { 2 name: string; 3 age: number; 4 email?: string; 5 } 6
1 const defaultProps: Partial<Props> = { 2 email: "example@example.com", 3 }; 4 5 const MyComponent: React.FC<Props> = ({ name, age, email }) => { 6 return ( 7 <div> 8 <h1>{name}</h1> 9 <p>{age}</p> 10 <p>{email}</p> 11 </div> 12 ); 13 }; 14 15 MyComponent.defaultProps = defaultProps; 16
By using “Partial<Props>”
, we indicate that the “email” prop is optional. By defining the default props object with the “Partial” type, we ensure that the default props object only contains optional props. By setting the “defaultProps” object to “MyComponent.defaultProps”, we ensure that the default props are used when the component is rendered without the prop.
React components can receive children as props. TypeScript can define the type of the children prop.
1 interface Props { 2 children: React.ReactNode; 3 } 4 5 const MyComponent: React.FC<Props> = ({ children }) => { 6 return <div>{children}</div>; 7 }; 8
By using “React.ReactNode”, we indicate that the component can receive any valid React node as its children. This approach helps to create reusable and flexible components.
In React, event handlers are commonly used to handle user interactions. TypeScript can define the type of event handlers.
1 interface Props { 2 onClick: (event: React.MouseEvent<HTMLButtonElement>) => void; 3 } 4 5 const MyComponent: React.FC<Props> = ({ onClick }) => { 6 return <button onClick={onClick}>Click me</button>; 7 }; 8
By defining the type of the “onClick” prop, we ensure that the prop is an event handler for the “button” element. By using “void”, we indicate that the event handler does not return a value. This approach helps to create more predictable and maintainable code.
In React, refs are used to get a reference to a component or element. TypeScript can define the type of the ref.
1 interface Props { 2 inputRef: React.RefObject<HTMLInputElement>; 3 } 4 5 const MyComponent: React.FC<Props> = ({ inputRef }) => { 6 return <input type="text" ref={inputRef} />; 7 }; 8
By using “React.RefObject<HTMLInputElement>”
, we indicate that the “inputRef” prop is a ref to an “input” element. This approach helps to create more reusable and flexible components.
In conclusion, these advanced TypeScript techniques for React function
TypeScript with React Function Components has several key benefits such as Type safety, Improved code readability, Better tooling, Easy collaboration, and Enhance scalability.
Imagine you're building a React app that allows users to search for and book flights. As you're building the app, you realize that the data structure for a flight reservation is quite complex, with nested objects and arrays.
If you were using plain JavaScript, you might run into issues with type mismatches or null values, which could cause runtime errors and impact the user experience.
However, if you were using TypeScript with React Function Components, you could define interfaces that describe the shape of your flight reservation data, like so:
1 interface FlightReservation { 2 flightNumber: string; 3 departureTime: Date; 4 arrivalTime: Date; 5 passengers: Passenger[]; 6 // ...other properties 7 } 8 9 interface Passenger { 10 firstName: string; 11 lastName: string; 12 age: number; 13 // ...other properties 14 } 15
By defining these interfaces, you're not only making the code more readable and understandable, but you're also providing static type checking that can help catch errors early in the development process.
For example, if you tried to assign a string to the “passengers” property instead of an array of “Passenger” objects, TypeScript would raise an error and prevent the code from compiling. This can save you valuable debugging time and ensure that your code is always reliable.
In addition to type safety, TypeScript provides better tooling that can help improve developer productivity. For example, you can use Visual Studio Code to get autocomplete suggestions, hover over variables to see their type and more.
Overall, using TypeScript with React Function Components is a powerful tool for building complex, scalable, and reliable React applications.
In the blog you have learned about the React Function Components, why they are preferred over the class components, the advanced TypeScript techniques, and the importance of using TypeScript with React Function Components.
By incorporating these techniques into your React development workflow, you can take your skills to the next level and build more robust, efficient, and scalable apps.
Moreover, you can accelerate your app development with DhiWise React Builder. The platform supports both TypeScript and JavaScript. It offers advanced features for Figma design to code generation, UI customization, team collaboration, code sharing as well as deployment.
So why wait? Start implementing your knowledge into the React project today with DhiWise and see the difference it can make for you and your team.
Happy coding!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.
Tired coding all day?
Do it with a few clicks.