2

React Best Practices - Ways To Write Better Code in 2022

 2 years ago
source link: https://dev.to/nourdinedev/react-best-practices-ways-to-write-better-code-in-2022-37gk
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Writing Code that is clean, scalable and easy to maintain, is the dream of every programmer, this ability separates a good programmer from a great programmer, The cool part is that there's always something to learn and to improve on, So you must be alert to tune with the React Best Practices.

folder-structure

A good folder structure depends on the size of your application and your team. So there's no general answer to that. Especially because this is a highly opinionated topic and depends also on personal preferences.

Having a clean folder structure when planning or starting your application can make a huge difference on the long run.

There is two main points you should follow when structuring your project, Avoid too much nesting, Don't over-engineer it.

└── /src
  ├── /assets - Contains static assets such as  images, svgs, company logo etc.
  ├── /components - reusable components like navigation bar, buttons, forms
  ├── /store - redux store
  ├── /utils - utilities, helpers, constants.
  ├── /views/pages - majority of the app pages would be here
  ├── index.js
  └── App.js

Enter fullscreen mode

Exit fullscreen mode

Code Structure

There's basically no defined structure, but you should have a style to follow throughout the codebase like:

  • Maintain a structured import order

Make sure all your imports statements are on new lines, as this will make your imports clean and easy to understand for all the components, third-party libraries, etc.

  • double quotes (" ") or single quotes (' ')

It's easy to get confused about whether to use double quotes (" ") or single quotes (' ') while working with React. The simple answer is: maintain consistency whatever you're using.

  • Divide the whole app into small components

Dividing the whole app into small components and then working on it on a separate file is a good practice to maintain clean code.

  • Follow common naming conventions

The meaning behind naming conventions is to easily recognize what type of element you're dealing with and to have something in your code that is common in the community.

  1. Name your file the same as the React component inside that file For example:

❌announcement-bar.jsx

✔️AnnouncementBar.jsx

  1. Use well-descriptive names for your variables so that even a third party or new developer can easily understand you code.
   const message = 'Good afternoon, Mr. Jhon';
   const wm = 'Good afternoon, Mr. Jhon';
   const m = 'Good afternoon, Mr. Jhon';

Enter fullscreen mode

Exit fullscreen mode

   const welcomeMessage = 'Good afternoon, Mr. Jhon';

Enter fullscreen mode

Exit fullscreen mode

  • Avoid Repetitive Code

If you notice you are writing duplicated code, convert it into components that can be reused.

  • Use Object Destructuring For Props

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

   const Button = (props) => {
      return <button disabled={props.isDisabled}>{props.text}</button>;
   };

Enter fullscreen mode

Exit fullscreen mode

   const Button = ({ text, isDisabled }) => {
      return <button disabled={isDisabled}>{text}</button>;
   };

Enter fullscreen mode

Exit fullscreen mode

JavaScript Code

Use a linter

A linter basically observes the JavaScript code you're writing and reminds you of errors you'd more likely catch when executing the code.

When you're using create-react-app, there's already ESLint configured, but you can also set it up completely on your own or extend the rules of a pre-configured ruleset.

ESLint

Extract reusable logic into custom hooks

Hooks allow us to reuse stateful logic without changing our component hierarchy.

Whenever you find yourself in a situation where you have to reuse the same stateful logic that is already used in another functional component, that's a great time to create a custom hook. Inside it you encapsulate the logic and just have to call the hook as a function inside your components.

React Hooks

Write a fragment when a div is not needed

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

for example we wrap the <h1> and the <p> in a <div> element, the issue with this approach is the usage of Unnecessary <div> elements.

return (
   <div>
      <h1>Hello!</h1>
      <p>
         Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum
         odio odio, tempor non ipsum et, aliquam pharetra urna.
      </p>
   </div>
);

Enter fullscreen mode

Exit fullscreen mode

The best way to wrap element in React is to use React fragment <React.Fragment> or the short syntax <></>

return (
   <>
      <h1>Hello!</h1>
      <p>
         Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum
         odio odio, tempor non ipsum et, aliquam pharetra urna.
      </p>
   </>
);

Enter fullscreen mode

Exit fullscreen mode

Integrate Typescript

Using TypeScript has many upsides like static type checking, better code completion in your IDE (intellisense), improved developer experience, and catching type errors while you write the code.

There may be reasons you don't want to use TypeScript inside your React application, for example if your project is very small integrating TypeScript can be a waste of time.

Test your code

During the time you're writing tests you're already in the thinking process of how to organize your code in order to pass this test. For me this is always helpful because I recognize what pitfalls might arise and that I have to keep an eye on them.

Tests can also serve as a kind of documentation, because for a new developer who is new to the codebase it can be very helpful to understand the different parts of the software and how they're expected to work.

Always start writing your tests at the beginning of the project especially unit and integration tests, because writing thos tests late in the project can be difficult and takes more time.

Conclusion

Although React is somewhat flexible in terms of how you can use it, following specific practices will help you get the most out of your experience.

Just remember, it's always all about adapting what's useful for you. So, don't take it all for granted and think about what might be helpful in your situation. Then you can just add it to your own stack of best practices.


Also read:
How to Render a 3D Model of You in React Using Three.js
10 JavaScript One-Liners - Ways To Boost Your Productivity


My blog
My website
Find me on Upwork
Find me on twitter
Find me on linkedin
Find me on github


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK