React Tips and Tricks

Written by Software Engineer

April 5, 2022
React Tips and Tricks

React has been around for a long time now and as with any popular library over time best practices and proposals for building robust applications that are easy to maintain and deliver a great experience to your users have come and gone. In this article we’ll go through some tips to help keep your code solid, components maintained and users delighted with a great experience.

Keep your components small


The longer a file grows, the harder it is to work with. It sounds silly, but the more you pack into one file - both in terms of functionality and sheer number of lines - can impact how easy it is to work with that file and navigate it. I find myself getting very easily lost in large files, and much prefer having code split into smaller files that I can have open side by side. With that in mind, here’s some things to consider when thinking about the size of your components:

  • Is the component doing too much? I like to have each component responsible for one small piece of UI. For example, if I’m building an e-commerce website I wouldn’t build one component that showed off all the images, details and pricing for an item on sale; I’d break it down into multiple components.

  • Does all the code need to live inside that one component? Can some of the code live outside of your component as plain old JavaScript functions? Keep reading for more on this concept…

  • Keep an eye on the size of your component’s render method (or if you’re using functional components, the size of the entire function). If this gets too big, that’s often a sign that you can split it out.

  • Similarly, track how much DOM your component is rendering. Is it rendering just one div with some text? Sounds good! Is it responsible for rendering vast quantities of elements? Perhaps it can be divided up.

Remember that in tech the answer can often be “it depends” - whilst you can follow the guidelines above (and any others you may have) - sometimes you’ll just have to go with your gut and see how you feel when working with files in your codebase.

Keep logic out of components


Building on the last section, often it can be tempting and very easy to overload our components with large blocks of code that do not need to be defined within the component. Components are responsible for the user interface, and as such try to keep only code that relates to that within them. For example:

  • A component that renders a UI to let users enter a username and password would not also contain the code that checks if a password is correct and logs the user in. That code would exist separately, and be called by the component. That way the component is only responsible for the UI, and delegates the actual act of logging in to another part of the codebase that doesn’t have to care about the UI.

  • A component that renders a list of a user’s latest tweets might not fetch the tweets itself, but be passed them as a prop, thus making it only responsible for rendering the data, not for fetching it. We might have another component responsible for fetching the data and potentially showing a loading spinner whilst the request is happening.

Test your components


In the past testing code that was responsible for the user interface was tricky, but with React being a mature piece of software plenty of solutions have risen for writing tests for your components. There are many different options you can consider, and you'll usually need two different parts that make up a test suite: the test runner, and the test library.

The test runner is the tool responsible for executing your tests and reporting on the results; the most popular test runner for React applications is Jest (also built by Facebook) but depending on your setup you may like to explore others such as:

  • Karma - originally built by the Angular team but can be used to test any frontend code.
  • Mocha - a very popular test runner mostly used in the Node community but can also be used to test browser applications.
  • Vitest - if you're using the increasingly popular Vite build tool, you might like to checkout Vitest which will pair nicely as a test runner. Be warned that Vitest is early in its development, but looks like a great tool.

Once you've got a test runner, you'll want to find a library that lets you test React components easily. These days most people reach for React Testing Library, which is a very mature and reliable test solution. Using this is a great pick because it's very popular in the community and you'll be able to find lots of resources for it.

Use ESLint React checks for robust hooks


React 16.8 introduced hooks, a new way of writing React components in a purely functional manner whilst enabling the ability for these components to have state and run side-effects such as fetching data from a server. Side-effects are managed via the useEffect hook, but it can often need to be used in with caution:

  • When using the useEffect hook you must also pass in your dependencies that should cause the hook to re-run.
  • If you forget these, it’s very easy to make your component’s effect run recursively and infinitely, causing your component and most likely your entire application to crash!
  • Depending on the context, you may often need to use additional hooks such as useMemo or useCallback to help React re-render efficiently.

These scenarios can be understood more by reading the hooks documentation, but the React team also maintain a set of ESLint rules that will error when you use useEffect in a way that may cause problems. I highly recommend using this - it’ll definitely save you from making your browser crash!

Try running the upcoming React releases


The React team makes an effort to clearly communicate any upcoming versions and any changes in the React codebase that may cause you some work to upgrade. You can get ahead of this by:

  • Keeping an eye on the React blog and twitter page for news on upcoming changes.

  • Trying upcoming versions yourself; React ships an experimental build regularly to npm that contains upcoming changes. These are experimental versions and I do not recommend using them in production, but it can be fruitful to install them locally and give them a test; it may give you a heads up about future work you might need to keep on the latest React version.

Whilst this may seem like extra work, it’s always worth trying to stay up to date and have your code working on the latest React version. Not only do new versions contain new features, but they also contain bug fixes and performance improvements which you’ll want to benefit from.

Use StrictMode


StrictMode is a special React component that you can wrap around your application. When your application is rendered, StrictMode will perform additional checks (only in development - not in production) to try and identify a variety of issues:

  • It will try to warn you about anything that may prevent you from upgrading smoothly to the next version of React.

  • It will detect usage of old legacy APIs that the React team would like to deprecate, and help you learn how to replace them.

  • It will also likely be extended in the future with more checks, so it’s worth adding now and keeping around your application at all times to make sure you’re able to keep your code up to scratch.

Scope CSS to each component


Out of the box React doesn’t come with any strong opinions about CSS, but one of the best benefits of using components is the ability to have the CSS for each component self contained within each component, avoiding one of the common CSS challenges where CSS from other parts of your application can unexpectedly clash with each other.

Just because React doesn’t provide a solution out of the box, that doesn’t mean you shouldn’t think about what’s best for you and your application! There are many directions you could take:

  • Use CSS Modules to have your CSS scoped to each component.

  • Write your CSS in a CSS-in-JS library that couples nicely with React. The Styled Components library is one of the most popular, along with Emotion, but there are plenty of other options so it’s worth exploring the space.

  • If you’re just getting started with a basic React app, you can apply inline styles on elements (style = {color: ‘red’}). This isn’t a recommended long term approach but can be enough for a very small side project or demo application.

Use fragments to avoid superfluous DOM


One of the issues with React applications can be the sheer amount of DOM that is rendered. This is in part because React components must have one top level DOM element. If your component needs to render a heading and a paragraph, they must be wrapped in a top level parent element so that React can function correctly.

Rather than use a generic HTML element like a div, you can instead use React Fragments. These let you wrap multiple elements together without inserting any extra elements into the DOM.

Conclusion


I hope this article has given you some things to try and explore within your own React applications to improve your code quality, maintainability and robustness. With each new version of React comes

Frequently Asked Questions

Do I need to know how to code to use WordPress?

Definitely not. There’s no need to learn coding, since most WordPress users aren’t developers. There’s many plugins and themes you can use to customize your website without coding.

What makes a certain domain valuable?

Valuable domains are usually memorable, easy to spell, pronounce, and short.

Will my hosting plans include data backups?

Yes. Verpex includes backups as part of its shared hosting and dedicated hosting plans.

How much memory does a site need?

512 MB of memory is needed for a small site with 500 or 1000 visits per day to work normally.

Jivo Live Chat