Web Age Solutions Inc
Providing Technology Training and Mentoring For Modern Technology Adoption
Web Age Aniversary Logo
US Inquiries / 1.877.517.6540
Canadian Inquiries / 1.877.812.8887

React Tutorial
The Top 10 React Best Practices in 2021

React is continually evolving and so are the best practices for using React.

 

Stay ahead of the changes!

 

Learn the best practices that reflect the current state of React in the 2nd half of 2021.

 

Keep Reading . . .

React Tutorial React Best Practices

What are the Top 10  React Best Practices for 2021?

React continues to evolve, improving seemingly monthly. Therefore, the best practices for using React should change as well.

In this React tutorial, we discuss the React best practices that reflect the current state of React in the 2nd half of 2021.

These React best practices fall into 3 neat categories:

#1 – Clean coding

 

React Tutorial React Best PracticesKeep components small

React Tutorial React Best PracticesName components well

React Tutorial React Best PracticesOrganize components consistently

 

#2 – Styling best practices

 

React Tutorial React Best PracticesPut local styles in a const called ‘styles

React Tutorial React Best PracticesPut branding-level styles in a CSS file

#3 – Modern techniques

 

React Tutorial React Best PracticesAvoid prop drilling with useContext hook

React Tutorial React Best PracticesLeverage a state container

React Tutorial React Best PracticesStop writing class-based components

React Tutorial React Best PracticesEmbrace the useState hook

React Tutorial React Best PracticesMaster the useEffect hook

React Tutorial React Best PracticesUse React fragments

React Tutorial React Best PracticesMemoize components

React Best Practices

Fill in the form and get the React Programming in 2021 course at 50% off! 

Regular Price: $1995
Discount Price: $998

 

Here are the Top 10 React Best Practices You Need to Know for 2021!

(With TWO BONUS Suggestions!)

React Tutorial React Best Practices

React Best Practices #1 – Keep components small

Small functions are much easier to understand than larger ones.

 

React Tutorial React Best Practices

 

So Present-day Developer, be kind to Future Developer and keep your functions as small as practical. React is very tolerant of refactoring. When your component — especially the JSX — becomes difficult to parse visually, break it into two smaller components. Heck, consider three or more components!

You pay zero performance hits and have everything to gain in speed of development.

 


Many smaller components

is better than

fewer large components.


React Best Practices #2 – Name components well

This is an underappreciated skill and oh so important!

It’s the front line of clean code. If they’re named in a predictable way, components are easy to find and easy to comprehend immediately.

Ideally another dev should know what your component does without even editing it.

Don’t worry about making the names short – characters are cheap but developers’ time is costly.

Yes, I know we’re writing them as functions which are normally named as verbs but we’re not running these functions. We’re placing these functions. They are all a thing on the page. Therefore, components should be named as a noun, not a verb. That noun should describe what it is that is being displayed on the page.

When searching for a name, say to yourself “This component is going to display (a) ________”, and whatever goes in the blank is the name of your component.

React Tutorial React Best Practices

Don’t Miss Out!

See our list of FREE
Upcoming Webinars!

 

VIEW NOW

How to Create React Applications Using Typescript

 

Watch now and take a look at the setup needed to code React components in TypeScript,
and then write actual components using TypeScript.

Related Course:  WA2583 React JavaScript Programming

React Best Practices #3. Organize your React components consistently

JavaScript is pretty flexible about where you put things. But just because you can put your functions and variables anywhere doesn’t mean that you should put them anywhere.

Do yourself and your teammates a favor; put just a little thought into the organization of your React components and stick to it.

Have a five-minute meeting, decide the order your team likes and then enforce it through code reviews or custom eslint rules.

Here’s an order that I’ve found to be logical:

 

  1. imports – At the top (obviously)
  2. setup/prep – The function declaration itself, hooks, and component-scope variables.
  3. presentation – Keep the JSX as near to the top as possible. After all, this is the reason for our component.
  4. logic/functions – Supporting logic for the presentation/JSX. These are generally in the order in which they are called above.
  5. styles – Declared as a single const object called “styles”.

 

react best practices

React Best Practices #4 – Put local styles in a const called ‘styles’

There are four different methods to style a React component. You can pick and choose the best technique for any situation, even combining techniques within the same component — they’re not incompatible. So, which should you choose in a given situation?

Styles that are local to a component should be written as JavaScript objects inside the component. This makes them A) easy to find for someone maintaining your code and B) encapsulated — fully local — to this component so that a change here won’t affect any other components. Heck, it can’t affect other components.

<div style={styles.productCard}><MoreJSXHere /></div>

Then at the bottom of the file, add this:

const styles = {
  productCard: {
    width: “50vw”,
    boxShadow: “2px 5px 7px #8790A0”,
  }
}

React Best Practices #5 – Put branding-level styles in a CSS file

On the other hand, styles that the branding team would care about — corporate colors, fonts, logo image, standard sizes of text — should be set in traditional external CSS stylesheet(s).

With React, you can import your site.css file in any component and it will be seen by every component in your entire app. I’m recommending that it be put in App.js because that is where the other devs will expect it to be. That’s where they’d go looking for imported CSS files.

import ‘./site.css’;

Exactly how it works isn’t important but if you’re curious, the import signals webpack to transpile that CSS into JavaScript, minify it, and bundle it so it’s pulled in with all the other JavaScripts. Super-efficient!

 

Local styles Global styles
Defined INSIDE the component Defined OUTSIDE all components
Private to the component Seen by every component
Safer Easier

React Tutorial React Best Practices

View our Complete React Training Course Catalog 

React training with Web Age covers all of the essentials of React and will give you the skills and foundation you need to work with this powerful library.

Start now!

Learn React from the experts!

LEARN MORE

React Best Practices #6 – Avoid prop drilling with useContext hook

Prop drilling is when a component receives a prop from its parent and passes it down to a child. We do it when we need to send data from a component to its grandchildren or great grandchildren or even lower. It’s a bad practice. You can avoid it with the useContext hook.

React Tutorial React Best Practices

useContext essentially creates a global variable whose value you set up high in hierarchy. Any component beneath that can ‘reach up’ and grab that data.

Here’s how to create a context variable called ThemeCtx and give it a value:

export const ThemeCtx = createContext(“”);
export function App() {
    return (
     <ThemeCtx.Provider value=”dark”>
          <Toolbar />
     </ ThemeCtx.Provider>
    );
}

And here’s how to read the value:

import { ThemeCtx } from ‘./App’;
import { useContext } from ‘react’;
const MyComponent = props => {
  const theme = useContext(ThemeCtx);
  return (
    <section style={{ …styles.container[theme] }}>
      <h1 style={{ …styles.heading[theme] }}>Title</h1>
      <button style={{ …styles.button[theme] }}>Go</button>
    </section>
  )
}

It’s a lot more code than prop drilling but it’s also easier to debug.

Note that using a state container eliminates the need for useContext. Speaking of which …

React Best Practices #7 – Leverage a state container

React has a long list of strengths. State management is not on that list.

Fortunately, several state management libraries have been written by some very smart developers. These come in a variety of shapes and sizes, some better than others, some easier to use than others. But what they all have in common is that they allow React components to share data — state in particular.

When state is changed in one component, any others who need that data have controlled access to it. The emphasis is on “controlled” here. They can safely share data and still remain relatively encapsulated.

The top choices:

 

Redux – Far and away the most popular choice, lots of help from the community, but extremely steep learning curve.
MobX – A distant second most popular choice. Less code to write because it uses a reactive model. Still tough to learn.
Recoil – Newest option on this list so the community support isn’t as prevalent but it is from Facebook Labs so it is becoming popular quickly.

 

With any of these, if you work at it just right, you can limit your stateful components to just one – the top level component.

And for all your stateful components …

React Tutorial React Best PracticesTech Blogs That Every IT Person Should Read.

Stay Updated. Learn about the latest technologies that are emerging in our market.

READ MORE

React Tutorial React Best Practices

2021 Must Learn Technologies & Top Courses 

Want to stay ahead of your competition?
View the Top Courses & Technologies you must learn for 2021!

VIEW NOW

 

React Best Practices #8 – Stop writing class-based components

Look, I get it. We OO developers like using classes. And since React will allow you to write your components as class-based components, Java/C# developers lean toward write classes. We need to resist this urge.

Class-based components are more complex and harder for you and your teammates to understand at a glance. They’re less abstract.

Your teammates will thank you when they’re having to maintain your components if you write them as functional components.

A few years ago we were forced to write class-based components any time we needed to use lifecycle methods or maintain state.

With the introduction of React hooks, we’re no longer required to write classes. So don’t.

And how exactly do we handle state then? Here’s how …

Using React Hooks

Watch our React Training video and learn
how to use the most common React hooks
including useState, useEffect and useContext..

Related Course:   WA2583 React Programming in 2021

React Best Practices #9 – Embrace the useState hook

“I need class-based components to maintain state!”, someone says. That’s no longer true with useState. For performance reasons, React components are immutable but using the useState hook provides a way to rerender a component after having changed a variable (aka. “state”).

import { useState } from ‘react’;
export function Foo() {
    const [ someData, setSomeData ] = useState(“”);
    return (
    <>
        <p>{ someData }</p>
        <button onClick={() => setSomeData(Math.random())}>Go</button>
   </>
}

In the code above, setSomeData is a function that will re-draw this component after having assigned the someData variable. Clicking the <button> will put a random number in someData and then redraw.

This is a simple example, I know. But useState is that easy.

React Best Practices #10 – Master the useEffect hook

Lifecycle events are the other reason we needed class-based components. Before React 16.8, we were forced to write class-based components if we needed to tap into the lifecycle events like ComponentDidMount and ComponentDidUpdate.

Fortunately today, useEffect fills that need by allowing us to simulate React lifecycle events.

I’ve got to warn you; useEffect isn’t easy to get your mind around, but it is almost a requirement in modern React development.

React Tutorial React Best Practices

Here’s a quick reference.

To run the first time the component renders (componentDidMount)

useEffect( () => {
   // Your setup code goes here.
}, [] );

To run each time the component updates (componentDidUpdate)

useEffect( () => {
    // Your updating code goes here.
});

To run just before the component exits (componentWillUnmount)

useEffect(() => {
     // returned function will be called on component unmount
     return () => {
    // Your cleanup code goes here
     }
}, []);

Bonus! React Best Practices #11 – Use React fragments

Quiz for React developers: What do we do when we get this message?

 

Failed to compile.

./src/App.js
Line 18:  Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>…</>?

 

Many developers will wrap their components in a <div> to create a single root component. This is not wrong but it is also not best.

Best practice is to use a React fragment like this:

<>
     <Component1 />
     <Component2 />
</>

React fragments look like you typed in a <div> or <section> or whatever but forgot the words. It is a set of empty angle brackets.

The beauty of React fragments is that 1) they’re not rendered, thus making your code a little smaller.2) they communicate your intent better to other developers.

Because they can’t be styled nor have attributes, we know that these are only here to wrap your component and for no other reason.

Bonus! React Best Practices #12 – Memoize components

When you ‘memoize’ a function, you run it once and remember its result so that you never have to re-run it. It can often help with performance.

Little known fact: the term “memoize” was coined when an MIT PhD candidate misspelled it in her dissertation. She was trying to say “memorize” but the term stuck.

Okay, that’s a total lie. But it makes for a good story, right? React Tutorial React Best Practices

We often write and run inner functions in React components. Every time we re-render this component, the function runs again, usually with the same results. It’s a waste of time. To prevent that, memoize the function with the useMemo().

const result = useMemo(() => someFunc(foo), [foo]);

This says that on every re-render, if foo hasn’t changed from the previous render, don’t rerun it. Instead use the value from the last render.

Now this is cool and all but larger gains can be found when memoizing entire React components:

function OptimizedParent(prop1) {
   const [state1, setState1] = useState({});

   const memoizedComponent = useMemo(
      () => <SomeComponent prop1={prop1} />, [prop1]);
    return (
      <>
       <SomeComponent1 />
       { memoizedComponent }
       <SomeComponent2 />
      </>
    );
}

In this example code, the memoized component will only be re-rendered if prop1 changes. If not, it is remembered from the prior render and merely … umm … placed.

Final Words on React Best Practices

We live in a technological era that moves fast, and this is especially true when you are to compete with the competitors in your business.

In this react tutorial, we discussed some React best practices that reflect the current state of React in the 2nd half of 2021.

Stay ahead of the changes! Visit our react training React Training page and learn to leverage the power of React in our hands-on React Training courses.

React training with Web Age covers all of the essentials of React and will give you the skills and foundation you need to work with this powerful library.

Our live instructor-led React Classroom Training courses will take you from the basics all the way up to building sophisticated, scalable web applications. Get started today!

React Programming in 2021

React Native Training Course: Building Mobile Apps with JavaScript

MERN Training

React Tutorial React Best Practices

US Inquiries / 1.877.517.6540
Canadian Inquiries / 1.877.812.8887