React Best Practices — You need to know!

Tanveer
5 min readApr 19, 2022

I’ve been working with React for a few years, during this time lot of learning has been made. As per my understanding, having good command over vanilla javascript helps you to master any tech involving javascript. To speed things up, go through the basics, understand how React works under the hood, and enjoy debugging.

With this post, I present you with some excellent best practices you might not have been aware of yet and try to help you become better React.js developers.

Use react-error-boundary lib for Error handling

Error is bound to happen and they are an inevitable part of programming. Error boundaries are introduced in React 16 as a way to catch and handle javascript errors that occur in the UI part of our components which catches errors that occur in lifecycle methods, render methods, and inside hooks like useEffect , but error boundaries won’t handle errors in event handlers, Async code, server-side rendering and error thrown in boundary itself. For more info visit React official doc.

react-error-boundary is a wrapper around the React’s ErrorBoundar and overcomes the limitation of the ErrorBoundary component. This allows us to utilize the withErrorBoundary function as HOC to manage problems within components. below is a simple example from react-error-boundary doc

Use useMemo to cache expensive operations

useMemo is one of the hooks offered by React. This is used to create memorized values , that are cached as long as it or it’s dependencies don't change. useMemo runs during rendering, where the main goal is not to avoid re-render in subcomponents:

  • useMemoshould be used when there is a high amount of processing
  • The threshold from when useMemo becomes interesting for avoiding extra processing highly depends on your application
  • Using useMemoin cases with very low processing, there can be extra overhead for its usage

here is simple abstract example ,

Use useReducer hook

The first question I had when I first read the React docs was “When should I use React.useReducer instead of React.useState. I’ve seen different opinions on this subject across the internet but I prefer React.useReducer when I need to update more than a single entity. I’ll explain with code.

We often resorted to React.useState as the default hook to keep the state in our components. However, over time the component state might need to get more complex depending on the new requirements like having multiple states. In certain cases, using a React.useReducer hook can help to avoid multiple state values and simplify update logic. Below is a simple example for React.useReducer

Use lazy loading/code splitting

Code-Splitting is a feature supported by bundlers like Webpack, Browserify, and Rollup which can create multiple bundles that can be dynamically loaded at runtime. Code Splitting is a method that helps to generate bundles that are able to run dynamically. It also helps to make the code efficient because the bundle contains all required imports and files.

With the help of code splitting, ‘lazy load’ can be implemented, which means just using the code which is currently needed.

As both React.lazy and Suspense is not available for rendering on the server yet now, it is recommended to use https://github.com/gregberge/loadable-components for code-splitting in a server-rendered app. React.lazy is helpful for rendering dynamic import as a regular component.

Extract reusable login into custom hooks

As we know, Hooks allow us to reuse stateful logic without changing our component hierarchy. If you find the same logic is repeated in different components, then it can be converted into to hook, which will encapsulate the logic and just have to call the hook as a function inside your components.

Object literals instead of switch

The most case when we need to use conditional statements we prefer to use if/else or switch cases. The problem with the switch case is that it doesn't perform so well. We can make use of simple object literal as shown below example.

Use object destructuring for props

The restructuring assignment syntax is a JS expression that makes it possible to unpack values from arrays or objects into distinct variables.

Use a fragment when a div is not needed

A react component can only render one single HTML tag at its root level. So if you’d like to render two adjacent elements you need to wrap them in another element.

Test your code

As we know testing ensures code integrity, It’s a good practice to write test cases for each component developed as it reduces the chances of getting errors when code is deployed on production. Refer official react doc for more details.

That’s it! Thank you for reading , and Happy coding.

If this article was helpful please like and share. You can connect and follow me on LinkedIn, Twitter, or Github.

--

--