Hi everyone! I hope you're safe and good.
I want to talk about something different today. I want to share some tips and strategies that will help you write cleaner and better code in react.
Most of what I've written or will write in the future are about things I found difficult when I was learning to code.
As a self-taught Developer without a mentor, one of the things I found difficult was writing a clean code in react.
I know I had to get better. But how?
So I came up with a solution. Find 5 respected and professional react developers, go to their GitHub repo and find a common thing or/and pattern in their react project.
I was not trying to compare my code with anybody's. I just want to find out what these so called professionals add to their code, how they implement somethings, approaches they take and why.
As expected, things started popping out, things that are missing in my code and present in all five. Everything started to make sense. For example why add prop-types to your workflow when it's not required.
TL;DR
From that day, I started including all what I learned into my workflow. And believe me, that helped me understand react and made my code not-so-newbie-like.
Enough with the talking. I will share some tips that learned from my research and also those that I learned via projects and experience.
Here are they not in any order.
1. Prop-types
If you're new to react, you might not know what's prop-types. However those that have been working with react have at least seen or work with it a couple of times.
What's prop-types?
Basically, prop-types is a module/ package or whatever you'd call it that provides type-checking to our props.
Let's say for instance, you are expecting an object prop from a parent element, and for some reason you receive an array. That will cause a total chaos to your app , inn'it?
Here's where prop-types come into the picture. You define what type of prop you're expecting and if you pass something contrary, it'd throw an error.
Const App = ({title, id, isCompleted}) => {
//
}
App.propTypes = {
Id: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
isCompleted: PropTypes.bool.isRequired
}
In the above code block , we have a component, app, that recieves three props — title, isCompleted and id. And below, we defined our prop-types, title should be a string, id should be a number and is isCompleted should be Boolean.
If we receive something contrary to what we defined, we'd get an error. That's the basic use case of prop-types. It can gets little complicated, but with time you'd learn.
Here's the link to the prop-types docs
2. Use functional components and hooks over classes.
Okay, this one is a little controversial. Some might agree with me, and other will not. I have used classes and lifecycle methods and if I have something to say regarding them, it'd be positive.
However, functional components and hooks are the future of react. React is making everything more favorable for hooks ( the react dev tools will back that claim).
In my opinion, if you're starting a new project, use hooks and functional components, but for existing codebases built with classes, don't refactor.
I personally like functional components. I mean, they are cleaner, elegant and simpler. Adding it to your workflow will significantly clean your code and make you a better Developer.
Using functional components and hooks shows that a Developer can adapt to the ecosystem. Couple of months ago, I was given a take away coding test by this company I was applying for a job. I did the whole project with hooks and the interviewer was pleased because "you're up to the trend" if I know what that means.
** I will Soon be writing a tutorial on advanced hooks soon **
3. Make your components small and reusable, but don't over abstract.
One the main feature of react is having everything in a component. Components in react are equivalent to Lego blocks — small chunks of code that build an app.
Your components should be relatively small. For example the send section of WhatsApp is a component right?
Inside that component, there's the send button component, voice message component and the text area component.
Everything is broken down into small, simple Chunks of code.
components should not only be small but also reusable. I'm not saying all components should be made reusable, only components that you know you're going to use again in another part of your application. A good example of a reusable component is a button.
If i want to create a button component, I will make it generic as possible. The size, color, Border-Radius will all be passed down as props.
That been said, you shouldn't over abstract your component. By over abstraction, I mean making all or most of your component generic.
Remember, A generic component is a component that you're sure you'd be using it in more than one place.
4. Destructure props. No more props.whatever.
This is one of my findings from the research I conducted. So before the research my code was like
const myApp = (props) =>{
///
<h1>{props.title.heading}</h1>
onChange={props.onChange}
}
Yep, ugly a** looking, I know. I can't recall the last time I did that though. Here's what I do now.
If the props is just one level deep
const myApp = ({title, onChange}) =>{
///
Const {heading}= title
<h1>{heading}</h1>
onChange={onChange}
}
And if it's nested, for example redux state I do something like this.
const myApp = ({chat:{messages}, settings:{themes}}) =>{
///
Const {sentMsg, recievedMsg}=
messages
Const {dark, light}= themes
<h1> Theme color {dark}</h1>
<li> {sentMsg} </li>
}
Obviously, destructing is prettier and cleaner than doing the props.title.... thing.
Destructuring cleans your react code and make it very readable and once again clean.
That's it guys! I hope you enjoy it and learn something from it.
Stay safe
Top comments (14)
Great writeup. I haven't seen prop-types used for a while, but that might just be because I use TypeScript. Other than that, I agree with all of the points. Especially the point about hooks and when to refactor to them. They're awesome.
Thanks Andrew. I've heard great things about using typescript with react, but I am yet to try it.
You went straight from 1 to 3 😊 all of this is pretty good. Would disagree that functional components are the future. I see so many people talk about hooks over classes. It all depends on the situation and the complexity of the component. Ever seen a complex component or something like a form with hooks? Awful. Messy. Impossible to follow.
Lol I haven't seen that. Thanks for pointing out.
I don't know understand what you mean by complex component. In context of form, I don't see how classes with be more beneficial than functional component.
I think it all depends on preference and like you said, situation.
Using eslint and prettier can be added but that would be "the way" for most of people
Just remove it and use web components.
Pardon?
Although that was a semi sarcastic comment, the reply tells a lot. "Become a better react developer by ignoring anything that is not react"? One true react dev would have argued why web components might not be a good alternative solution.
If he's something to say, why the sarcasm? I am sorry for not getting his sarcasm.
Amazing!
I am glad you liked it. Thanks.
Good article. This answered my question about why and when i should use class component based and function component based. I hope you write next about function component and advanced hooks use. 👍
How is hooks compared to using a Redux for example?
Hooks and redux aren't alternatives, they work together. Redux even comes with hooks: react-redux.js.org/api/hooks
Though a lot of apps that use Redux might not need it to begin with: simplethread.com/cant-replace-redu...