Hey Developers π!
I'll provide some Pro React tips in today's blog to help you become more proficient with React. Some of them may be familiar to you, but a few will be very special to you.
Letβs start with the first one!
Permalink1. Better Imports π
In a React app or any JavaScript/TypeScript project, you will have a messy folder structure and a lot of imports.
Let's assume you have a folder structure like this in your project
This is how your imports will look like
And it's gonna be even worse if you are importing in a file that is nested deeply.
To solve this, you can add a jsconfig.json
(or tsconfig.json
if you have a TypeScript project) and then add the following to it.
{
"baseUrl": ".",
"paths": {
"@/*": ["./*"]
}
}
This configuration will now essentially allow you to import folders like @/components
, @/utils
or @/hooks
etc from anywhere in the codebase.
Now your imports will look like this
Permalink2. Clean forms π§‘
Usually, in React, we use controlled inputs and that makes the code very messy.
This is what the code in a form with controlled input looks like.
Instead, what you can do is set the name
prop on the <input />
and then later you can get the value for all inputs using the FormData
class.
This is how the code will look now
const HomePage = () => {
const handleSubmit = e => {
e.preventDefault()
// Create FormData and convert it to an object
const form = new FormData(e.target)
const formData = Object.fromEntries(form.entries())
// Or use destructuring
const { firstName, lastName } = Object.fromEntries(form.entries())
// API and backend call
}
return (
<div>
<form onSubmit={handleSubmit}>
<input name="firstName" />
<input name="lastName" />
<button type="submit">Submit</button>
</form>
</div>
)
}
And the state is gone π
In this version, the code looks much cleaner and more readable compared to that version using controlled inputs with the state.
Essentially what is happening here is that we create a new instance of FormData
class, and we convert it to an object using Object.fromEntries()
and pass in the form.entries()
inside it.
Which in turn returns to us an object with the "name"
of the input
and the value is the text input by the user.
If you want to get even better handling than this, consider using a form library like
react-hook-form
,formik
or any alternatives. Thanks to Mohamed Moulay for suggesting this
Permalink3. Use Vite β‘
A lot of people use Create React App when building their React projects. Let me tell you there is a better alternative to Create React App.
You might have noticed the problems with the speed of Create React App. It takes a lot of time to create the project, takes a lot of time to start the project as well.
PermalinkEnter Vite
Vite is a super powerful tool that lets you create Vanilla, React, Preact, Vue, Svelte and Lit projects with TypeScript support π€―!
Vite is a lot faster than Create React App. Here's a video by Jesse Hall that shows how fast Vite is compared to CRA.
At the time this video was made, Vite had
@vitejs/app
command but now it has changed to justvite
To generate a Vite project, you just need to execute this command and then select the appropriate choices.
npm create vite
# or
npm init vite
Permalink4. Stretchy Props β
Have you ever seen something similar in your React app?
There are numerous props to send in and also, and the names of the props and their values are the same here. It becomes difficult to write all of it down.
A better way to pass in these props without repeating these names is like this
Here, you create an object with the properties you need to pass in called props
and then while returning the component, you spread the object to pass everything in. This makes the code developer-friendly.
Permalink5. SWR - A better way to fetch data πͺ
If you have done any sort of data fetching and displaying in a React app, you know how much work you have to do to make it better for the end user.
Usually, this is how you fetch data in a React app
With this "normal" way of data fetching, the user experience isn't that good
Instead, if we use swr
, that will make everything better because
- No state management
- No loading state management
- Refetch anytime
- Caching and much more...
The first step is to install the swr
library through NPM or the package manager of your choice
npm i swr
Once it's installed, go ahead and change your code to use SWR this way.
import useSWR from 'swr';
const fetcher = (url) => fetch(url).then((r) => r.json());
export default function App() {
const { data, error } = useSWR(
'https://jsonplaceholder.typicode.com/photos',
fetcher
);
if (error) return <div>failed to load</div>;
if (!data) return <div>loading...</div>;
return <p>{data[0].id}</p>;
}
One of the most killing features of SWR is that every time the window is focused, it refetches and updates the data in the background to get up-to-date data.
With that, you can also trigger the refetch manually using the mutate
function.
import useSWR from 'swr';
const fetcher = (url) => fetch(url).then((r) => r.json());
export default function App() {
const { data, error, mutate } = useSWR(
'https://jsonplaceholder.typicode.com/photos',
fetcher
);
const fetchAgain = () => {
mutate();
};
if (error) return <div>failed to load</div>;
if (!data) return <div>loading...</div>;
return (
<div>
<button onClick={fetchAgain}>Refetch</button>
<p>{data[0].id}</p>
</div>
);
}
Read more about SWR here
If you want more control over your data fetching, mutations and caching, React Query/Tanstack Query might be better for you instead of SWR
Written by
I am a full stack developer, YouTuber and blogger!
I am a full stack developer, YouTuber and blogger!
Published on
FlyCode Blog
We help product teams work like software engineers - to ship better products faster with no code.
We help product teams work like software engineers - to ship better products faster with no code.