Reactjs application development tips

react
Back

In this article, I've summarized a few tips for writing better Reactjs applications. I've collected these tips while working on React/Nextjs applications over time. I hope this will be helpful to you.

Tip

Q: What are some helpful patterns/concepts/principles are useful while building React apps?

A:

Tip

Q: How to think in React?

A: Please read this Thinking in React offical documentation page.

Tip

Q: What are some important js concepts should be known to build React apps?

A:

Tip

Q: Why should create/develop tiny components?

A: Small components are easier to understand, test, and maintain.

Tip

Q: What are different types of components? Why should we logically seperate them out?

A:

Tip

Q: When to use React.PureComponent or React.Component?

A:

Example:

class Home extends React.PureComponent
// Instead of
class Home extends React.Component

Tip

Q: When to use useRef or useState hooks?

A: Use refs instead of state if you don't want to re-render component.

Tip

Q: When to use functional components(and hooks)?

A: Prefer functional components(and hooks) unless you need class components/React hooks will solves the problem of needing life cycle method.

Tip

If you are doing any async calls from componentDidMount, then might see below warning in your console.

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

To fix this please follow this link - https://www.robinwieruch.de/react-warning-cant-call-setstate-on-an-unmounted-component/

Tip

While rendering lists, you need to pass 'key' prop while iterating over items, don't use current index as key instead, try to use unique value(number or string) from current item or use extenal unique id generation libs like -

import shortid from "shortid";
<Comment key={shortid.generate()} /> OR
<Comment key={comment.ID} />

Tip

Dependency optimization - Don't import whole library if you need only few functions from it.

Example

import _ from 'lodash;
// instead do
import toString from 'lodash/toString';

Tip

Split code with React.lazy and use Suspense for off-screen components.

You can also use route-based and/or component-based code splitting techniques.

import React, { lazy, Suspense } from 'react';
const AvatarComponent = lazy(() => import('./AvatarComponent'));
const renderLoader = () => <p>Loading</p>;
const DetailsComponent = () => (
<Suspense fallback={renderLoader()}>
<AvatarComponent />
</Suspense>
)

How to - link

Tip

Use React.Fragment over unnecessary <div>

Don't add unnecessary dom element if you just want to wrap code.

Example -

render() {
return (
<React.Fragment>
Some text.
<h2>A heading</h2>
</React.Fragment>
);
}

Tip

Rendering large dataset? You can virtualize large lists.(think of tweets of Twitter)

react-window comes with components for efficiently rendering large lists and tabular data.

How to - link

Tip

Use constructor to bind event handlers instead of render function.

class Products extends Component {
constructor(props) {
super(props);
this.state = {
activeProductIndex: 0
};
this.onProductSelect = this.onProductSelect.bind(this);
}
...
}

Tip

Don't fetch it again, intead store it in global state/cache it.

For this you can use -

componentDidMount() {
let { users } = this.props;
// Means we've already fetched users, don't do it again
if (users.length) {
return;
}
// Get users from server
this.props.getUsers();
}

Tip

Always use ErrorBoundary to catch app runtime errors.

Tip

Try to avoid HOCs and Render props whenever possible. To solve such use-cases prefer React hooks.

Tip

Use react-devtool to debug performance.

Tip

Analyze your bundle size and code bloat

Use Source map explorer

source-map-explorer bundle.min.js
source-map-explorer bundle.min.js bundle.min.js.map
source-map-explorer '*.js'

How to - link

Tip

use useMemo and useCallback hooks to memorize heavy compulations, to cache repetitive components to prevent unnecessary re-renders.

Tip

Try not use dom manipulation libraries like jQuery, prefer plain javascript over.

May YOU MIGHT NOT NEED JQUER project will help here!

Well don't access DOM directly, instead use refs api.

Tip

Use Testing library instead of Enzyme or any other testing library. Reason is here.

Tip

Don't test implementation details

Tip

Don't pass it/store it, if you don't need it!

Don't pass unnecessary props to child components, don't save unnecessary states if you don't need them!

render() {
return (
<>
<WrappedComponent {...this.props} />
</>
)
}

Tip

Data mutation can cost, use pure functions and DRY.

Use Lodash js utility library for all kind of operations.

Tip

Prefer css-in-js libraries like styled-components over css/less/scss files.

“CSS-in-JS” refers to a pattern where CSS is composed using JavaScript instead of defined in external files. Read a comparison of CSS-in-JS libraries here.

Tip

Better to organize your app.

How to - link

Tip

Use classnames for naming dynamic class names or conditionally joining classNames together.

or can prefer clsx.

Tip

Prefer composition over inheritance.

Tip

Use Link instead of router.push because there is a huge problem when it comes to accessibility here.

function ClickButton(props) {
return (
<Link to="/next-page">
<span>Go to next page</span>
</Link>
);
}

Tip

Create new useEffect block to seprate concerns.

useEffect(() => {
// Data fetching
}, []);
useEffect(() => {
// Some other logic
}, []);

Tip

Use service worker for caching assets.

How to - link

Workbox is tool to generate service worker.

Tip

Understand React internals, VDOM.

Read React as a UI Runtime

Tip

Advantages of using Web components -

Hope above tips will be helpful for you to write better React apps.

Thanks.

MIT © Mohan Dere.
-