DEV Community

Cover image for 5 Tips Every React Developer Should Know
Tapajyoti Bose
Tapajyoti Bose

Posted on • Updated on

5 Tips Every React Developer Should Know

React is an amazing tool to build Front End Applications. This article will provide you some tips which you can immediately implement to up your React game and help you become a better React Developer, Write better code and even help you ace the interviews that you were initially scared of.

1. Lazy Loading

Lazy Loading is the design pattern which delays the loading or initialization of objects or resources until they are required. This improves performance drastically. In the case of React, the reduced bundle size leads to faster initial load time, which is crucial these days with dwindling attention span.

Luckily for us, React makes implementing Lazy Loading very easy for developers. All you need to do is wrap dynamic import statement import() with React.lazy.

Let's consider we have a Counter.js file.

// Counter.js
import { useState } from 'React'

const Counter = () => {
  const [count, setCount] = useState('');

  const increment = () => setCount(count => count + 1);
  const decrement = () => setCount(count => count - 1);

  return (
    <div>
      <button onClick={decrement}> - <button>
      <span> {count} <span>
      <button onClick={increment}> + <button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Lazy Loading the counter in App.js:

// App.js
import { lazy } from 'React'

const Counter = lazy(() => import('./Counter'));

const App = () => {
  return (
    <div>
    <Suspense fallback={<Loader />}>
        <Counter />
    </Suspense>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Counter will be Lazy Loaded only when it's required and the Loader component will be displayed while it is loading.

2. Custom Hooks

With the release of React 16.8, developers were introduced to React Hooks. In simple terms, Hooks are functions that allow you to implement additional features like the state and life cycle methods in the light-weight Functional Components, which were formerly limited to comparatively heavy-weight Class Components.

Apart from the Hooks provided by React out of the box, developers can also write their own Hooks to suit their personal requirements.

Let's say you need access to the window dimensions, you can create a useWindowSize Hook to solve the problem.

import { useState, useEffect } from 'react'

function useWindowSize() {
  const [windowSize, setWindowSize] = useState({
    width: 0,
    height: 0,
  })

  useEffect(() => {
    const handler = () => {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      })
    }

    handler()
    window.addEventListener('resize', handler)

    // Remove event listener on cleanup
    return () => {
      window.removeEventListener('resize', handler)
    }
  }, [])

  return windowSize
}
Enter fullscreen mode Exit fullscreen mode

3. React Fragments

React requires all your Components to return a single element. For a long time, this was a major issue, making you wrap everything in a div or use array notation.

const DivWrap = () => {
    return (
        <div>
            <ComponentA />
            <ComponentB />
        </div>
    )
}

const ArrayNotation = () => {
    return [
        <ComponentA key="a" />
        <ComponentB key="b" />
    ]
}
Enter fullscreen mode Exit fullscreen mode

After React 16.2, Fragment was introduced. It is a React element that you can use to group elements together but does not add any element in the DOM

import { Fragment } from 'react'

const Frag = () => {
    return (
        <Fragment>
            <ComponentA />
            <ComponentB />
        </Fragment>
    )
}

// Or after Babel 7
const FragNewSyntax = () => {
    return (
        <>
            <ComponentA />
            <ComponentB />
        </>
    )
}
Enter fullscreen mode Exit fullscreen mode

4. Dev Tools

React Dev Tools is an amazing extension available for Chrome and Firefox. It makes debugging your application a piece of cake by providing you all the details like props, state, hooks, and anything in between for each and every component.

Dev Tools

Fun Fact: You can also use it to partially dive into the code base of the websites of top companies such as Netflix, Twitter, Facebook and any other site using React

Netflix Dev Tool

5. Higher-Order Component (HOC)

Are you tired of adding the Navbar, Sidebar, and Footer to every page on your site? Higher Order Component (HOC) to the rescue!

HOC is an advanced technique in React for reusing component logic. It allows you to take a component and will return a new component with the functionality or data of the HOC included.

withRouter() or connect() are examples of some common HOCs.

Let's create a withLayout HOC which accepts an Element and automatically adds the Navbar, Sidebar and Footer with it.

const withLayout = (Element) => {
    return (props) => (
        <>
            <Navbar />
            <Sidebar/>
            <Element {...props} />
            <Footer />
        </>
    );
}
Enter fullscreen mode Exit fullscreen mode

Using the HOC

const Home = () => {
    return (
        <h1>
            I am Home!
        </h1>
    )
}

export default withLayout(Home)
Enter fullscreen mode Exit fullscreen mode

Wrapping Up

We are at the end of the article. Hope that I could provide you with some insights. Share your thoughts in the comments below.

Best of Luck with your React Development Journey!

Finding personal finance too intimidating? Checkout my Instagram to become a Dollar Ninja

Thanks for reading

Want to work together? Contact me on Upwork

Want to see what I am working on? Check out my GitHub

I am a freelancer who will start off as a Digital Nomad in mid-2022. Want to catch the journey? Follow me on Instagram

Follow my blogs for weekly new tidbits on Dev

FAQ

These are a few commonly asked questions I get. So, I hope this FAQ section solves your issues.

  1. I am a beginner, how should I learn Front-End Web Dev?
    Look into the following articles:

    1. Front End Development Roadmap
    2. Front End Project Ideas
  2. Would you mentor me?

    Sorry, I am already under a lot of workload and would not have the time to mentor anyone.

  3. Would you like to collaborate on our site?

    As mentioned in the previous question, I am in a time crunch, so I would have to pass on such opportunities.

Connect to me on

Top comments (17)

Collapse
 
willaiem profile image
Damian Żygadło

HOC is deprecated.

Collapse
 
ruppysuppy profile image
Tapajyoti Bose

So what's the replacement for HOC?

Collapse
 
devrithm profile image
Ahmed • Edited

I mean why use HOC and not just simplify it with a general Layout component

So simply speaking:

const Layout = ({children}) => {
   return (
      <Header />
      <main>{children}</main>
      <Footer />
   )
}

export default Layout;
Enter fullscreen mode Exit fullscreen mode

and than you can wrap any page or template you wish with your Layout component!

Thread Thread
 
ruppysuppy profile image
Tapajyoti Bose • Edited

Using the HOC is a more sleek solution. It still has the same issues as the HOC approach

Thread Thread
 
wutangpaul profile image
Paul McClean • Edited

"Sleek" is pretty subjective. I much prefer a layout component rendering child elements. It makes the HTML structure easier to read, in my opinion.

Thread Thread
 
ruppysuppy profile image
Tapajyoti Bose

I do agree, "sleek" indeed is subjective

Thread Thread
 
devrithm profile image
Ahmed • Edited

I also think Sleek is not KISS -> Keep it super simple ... please don't forget this industry is hungry for new people to join.

While the European software developer population is growing, it cannot keep up with the booming demand. In 2019, the number of software developers in Europe increased by 7% to 6.1 million. At the same time, demand for IT skills in Western markets is expected to grow by more than 10% in 2020!

Source: Ministry of Foreign Affairs
cbi.eu/market-information/outsourc...

What I am trying to elaborate here programming should be easier for newcomers, and simple to understand and in-order for them to learn they should follow the rabbit hole easy, don't you agree.

Thread Thread
 
ruppysuppy profile image
Tapajyoti Bose

😐

Collapse
 
willaiem profile image
Damian Żygadło • Edited

In 99% cases - hooks.

You can check also this post, if you really want to know:
medium.com/javascript-scene/do-rea...

Yes, HOC can be used, but only in niche scenarios that you won't encounter super often.

Thread Thread
 
ruppysuppy profile image
Tapajyoti Bose

If you work on a large project not using an HOC for layout will be a huge pain. The connect function was indeed replaced with hooks, but you would still need the withRouter HOC for quite a few cases

We both have different viewpoints. So, let's agree to disagree :)

Thread Thread
 
raibtoffoletto profile image
Raí B. Toffoletto

Am I wrong in understanding that Everytime you use HOC those components (nav, footer, ...) will be mounted and remounted?? I think better layout way is router and lazy loading, right? Or as said Hooks and Context.

The beauty of react-router is to nest as many switches as you need. And I so far haven't found an use for withRouter since useHistory and other hooks are available.

Thread Thread
 
ruppysuppy profile image
Tapajyoti Bose • Edited

The purpose of a separate layout would be to keep the routing logic separate from the ui logic. But you are correct about the re-rendering of the components.

I have used useHistory for only navigation, so I don't have enough knowledge to comment on how it compares to withRouter

Thanks for your input :)

Collapse
 
pengeszikra profile image
Peter Vivo

I never try to check facebook with dev tools ... it was so interesting.

Collapse
 
ruppysuppy profile image
Tapajyoti Bose

:)

Collapse
 
vladi160 profile image
vladi160

= <></>

Collapse
 
jprly profile image
jprly

Great code examples, thank you!

Collapse
 
ruppysuppy profile image
Tapajyoti Bose

Glad you found it helpful!