You know what it’s like to pick up a new language or framework. Sometimes there’s great documentation to help you find your way through it. But even the best documentation doesn’t cover absolutely everything. And when you work with something that’s new, you’re bound to find a problem that doesn’t have a written solution.
That’s how it was for me the first time I created a React project — and React is one of those frameworks with remarkable documentation, especially now with the beta docs. But I still struggled my way through. It’s been quite a while since that project, but the lessons I gained from it are still fresh in my mind. And even though there are a lot of React “how-to” tutorials in out there, I thought I’d share what I wish I knew when I first used it.
So, that’s what this article is — a list of the early mistakes I made. I hope they help make learning React a lot smoother for you.
Using create-react-app to start a project
TL;DR Use Vite or Parcel.
Create React App (CRA) is a tool that helps you set up a new React project. It creates a development environment with the best configuration options for most React projects. This means you don’t have to spend time configuring anything yourself.
As a beginner, this seemed like a great way to start my work! No configuration! Just start coding!
CRA uses two popular packages to achieve this, webpack and Babel. webpack is a web bundler that optimizes all of the assets in your project, such as JavaScript, CSS, and images. Babel is a tool that allows you to use newer JavaScript features, even if some browsers don’t support them.
Both are good, but there are newer tools that can do the job better, specifically Vite and Speedy Web Compiler (SWC).
These new and improved alternatives are faster and easier to configure than webpack and Babel. This makes it easier to adjust the configuration which is difficult to do in create-react-app without ejecting.
To use them both when setting up a new React project you have to make sure you have Node version 12 or higher installed, then run the following command.
npm create vite
You’ll be asked to pick a name for your project. Once you do that, select React from the list of frameworks. After that, you can select either Javascript + SWC
or Typescript + SWC
Then you’ll have to change directory cd
into your project and run the following command;
npm i && npm run dev
This should run a development server for your site with the URL localhost:5173
And it’s as simple as that.
Adding Vite to Your Existing Web App
Making a Site Work Offline Using the VitePWA Plugin
Parcel CSS: A New CSS Parser, Transformer, and Minifier
Using Parcel as a Bundler for React Applications
Using defaultProps
for default values
TL;DR Use default function parameters instead.
Data can be passed to React components through something called props
. These are added to a component just like attributes in an HTML element and can be used in a component’s definition by taking the relevant values from the prop object passed in as an argument.
// App.jsx
export default function App() {
return <Card title="Hello" description="world" />
}
// Card.jsx
function Card(props) {
return (
<div>
<h1>{props.title}</h1>
<p>{props.description}</p>
</div>
);
}
export default Card;
If a default value is ever required for a prop
, the defaultProp
property can be used:
// Card.jsx
function Card(props) {
// ...
}
Card.defaultProps = {
title: 'Default title',
description: 'Desc',
};
export default Card;
With modern JavaScript, it is possible to destructure the props
object and assign a default value to it all in the function argument.
// Card.jsx
function Card({title = "Default title", description= "Desc"}) {
return (
<div>
<h1>{title}</h1>
<p>{description}</p>
</div>
)
}
export default Card;
This is more favorable as the code that can be read by modern browsers without the need for extra transformation.
Unfortunately, defaultProps
do require some transformation to be read by the browser since JSX (JavaScript XML) isn’t supported out of the box. This could potentially affect the performance of an application that is using a lot of defaultProps
.
Demonstrating Reusable React Components in a Form
I Learned How to be Productive in React in a Week and You Can, Too
Props and PropTypes in React
Don’t use propTypes
TL;DR Use TypeScript.
In React, the propTypes
property can be used to check if a component is being passed the correct data type for its props. They allow you to specify the type of data that should be used for each prop such as a string, number, object, etc. They also allow you to specify if a prop is required or not.
This way, if a component is passed the wrong data type or if a required prop is not being provided, then React will throw an error.
// Card.jsx
import { PropTypes } from "prop-types";
function Card(props) {
// ...
}
Card.propTypes = {
title: PropTypes.string.isRequired,
description: PropTypes.string,
};
export default Card;
TypeScript provides a level of type safety in data that’s being passed to components. So, sure, propTypes
were a good idea back when I was starting. However, now that TypeScript has become the go-to solution for type safety, I would highly recommend using it over anything else.
// Card.tsx
interface CardProps {
title: string,
description?: string,
}
export default function Card(props: CardProps) {
// ...
}
TypeScript is a programming language that builds on top of JavaScript by adding static type-checking. TypeScript provides a more powerful type system, that can catch more potential bugs and improves the development experience.
Props and PropTypes in React
Putting Things in Context With React
An Overview of Render Props in React
Using class components
TL;DR: Write components as functions
Class components in React are created using JavaScript classes. They have a more object-oriented structure and as well as a few additional features, like the ability to use the this
keyword and lifecycle methods.
// Card.jsx
class Card extends React.Component {
render() {
return (
<div>
<h1>{this.props.title}</h1>
<p>{this.props.description}</p>
</div>
)
}
}
export default Card;
I prefer writing components with classes over functions, but JavaScript classes are more difficult for beginners to understand and this
can get very confusing. Instead, I’d recommend writing components as functions:
// Card.jsx
function Card(props) {
return (
<div>
<h1>{props.title}</h1>
<p>{props.description}</p>
</div>
)
}
export default Card;
Function components are simply JavaScript functions that return JSX. They are much easier to read, and do not have additional features like the this
keyword and lifecycle methods which make them more performant than class components.
Function components also have the advantage of using hooks. React Hooks allow you to use state and other React features without writing a class component, making your code more readable, maintainable and reusable.
Importing React unnecessarily
TL;DR: There’s no need to do it, unless you need hooks.
Since React 17 was released in 2020, it’s now unnecessary to import React at the top of your file whenever you create a component.
import React from 'react'; // Not needed!
export default function Card() {}
But we had to do that before React 17 because the JSX transformer (the thing that converts JSX into regular JavaScript) used a method called React.createElement
that would only work when importing React. Since then, a new transformer has been release which can transform JSX without the createElement
method.
You will still need to import React to use hooks, fragments, and any other functions or components you might need from the library:
import { useState } from 'react';
export default function Card() {
const [count, setCount] = useState(0);
// ...
}
Those were my early mistakes!
Maybe “mistake” is too harsh a word since some of the better practices came about later. Still, I see plenty of instances where the “old” way of doing something is still being actively used in projects and other tutorials.
To be honest, I probably made way more than five mistakes when getting started. Anytime you reach for a new tool it is going to be more like a learning journey to use it effectively, rather than flipping a switch. But these are the things I still carry with me years later!
If you’ve been using React for a while, what are some of the things you wish you knew before you started? It would be great to get a collection going to help others avoid the same struggles.
5 Mistakes I Made When Starting My First React Project originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.
source https://css-tricks.com/5-mistakes-starting-react/
No comments:
Post a Comment