Physical Address

Sagipora Sopore Baramulla 193201  Jammu & Kashmir

featured image

Reactjs best practices 2022, code this not that

Reactjs best practices which we really need to implement for a production-ready Reactjs app.

Some basic things to remember while writing Reactjs code:

Reactjs is a popular front-end library from Facebook. Although, Reactjs doesn’t care how you write Reactjs apps. But it’s important to follow some Reactjs best practices to keep our projects clean, secure, and scalable.

In this tutorial, we’ll talk about some of the Reactjs best practices which we really need to implement for a production-ready Reactjs app. Though these best practices are not mandatory they are important if seen from an experienced developer’s perceptive. Without further due let’s find out what are these best practices

01) Keep your code DRY:

keeping your code DRY is a general concept in programming and not limited to Reactjs. But it is important to not repeat code. If you repeat code, take the logic and functionality out to create a function.

The same is true for React components. For example, if you need to use a button multiple times in your react app. Make the button generic so that it can be used as per the requirement.

02) Remove unnecessary comments from the code:

Add comments where it’s required. Don’t use comments excessively in your code. So you don’t get confused if you later read your code again or try to change it.

Also, make sure your remove debuggers, console logs and other code used for development before releasing your react app.

03) Use Code-Formatters:

Formating your Reactjs code is harder than writing it. And when you have both HTML and JavaScript code in the same file, it becomes harder, as If it wasn’t hard enough already. Fortunately, there are code formaters out there in the world that make our life easy. One popular code formatter is Prettier.

04) Write more tests:

It’s good practice to take note of all the possible scenarios of a component before deploying it. Writing unit tests will go a long way to save a ton of hassle for you. Jest and Enzyme are some popular React-based unit testing frameworks.

05) Naming conventions:

Comments: Use all capitals for global comments e.g const DEFAULT_USER = “John Doe”

React components: Use the pascal case while naming react components e.g Header.js, Login.js, MainPage.js, etc

Normal JavaScript: Use camel case notation while writing JavaScript functions and variables e.g submitHandler(), initialState etc.

06) Use camelCase for prop naming:

Use camelCase notation while writing props. Although, it’s not a rule it’s a standard. And it makes your code readable to other programmers.

Reactjs architecture best practices:

07) Don’t use DOM attributes as prop names:

Do not use DOM attributes as prop names, it will make your code confusing. Thus other programmers working on your code will not expect them.

BAD:

<Input onClick="{addItemHandler}" />

GOOD:

<Input onAddItem="{addItemHandler}" />

Instead of using onClick which is a dom property for input element, use whatever your event does like onAddItem.

Also Read: 10 CSS pro tips, code this not that

08) Decompose into Small Components

To write clean Reactjs code, decompose large components into smaller ones. It will make your components lean and easy to debug and work with. Also, extract logic to different files to further simplify your components.

Also, create different folders for different items. For example, if you have two different components like Login and Logout components, you can put them in a separate folder with the name AuthComponents. Similarly, you can put them together with other related components in the different folders.

09) Use self-closing tags if possible:

If you have a component that doesn’t have children, it’s a good practice to use self-closing tags. Only use closing tags if you have to render children.

BAD:

<NewNoteForm> </NewNoteForm>

GOOD:

<NewNoteForm />

10) Use functional and class components as required:

If you want to render UI only use functional components since they are efficient in rendering UI. If you need logic inside your component prefer class-based components.

Furthermore, both classes and functional components are used excessively out there. In older codebases, you will definitely come across class-based components. So, it is better to learn to use both class-based and functional components. Also, functional components are preferred in modern Reactjs projects.

Also Read: Scss vs Bootstrap vs Tailwind CSS

Reactjs folder structure best practices:

11) Folder Layout:

It’s pretty important to have a solid folder structure to make your Reactjs scalable. Probably, it is the first step you will work on while starting a new Reactjs project.

Although, your project may differ based on the complexity and specification of your project, here are some guidelines that may be of help.

  1. Create two different folders for src and public files. Public files include index.html, favicons and other files. While as src files usually contains source code for your app. Src folder may include other folders like components, pages, store etc. Reactjs projects created with npm create-react-app creates these folders by default.
  2. In src folder create seperate folders for components, store and pages. Components will contain small components that can be used inside pages like Buttons, Cards etc. Store will contain your Reactjs app’s overall store, based on your requirement your app may not have a store. Lastly, put all of your pages inside pages folder. Pages may contain MainPage, LoginPage, PostsPage etc.
  3. Put related componets together. For example Login and Logout components can be put together inside a seperate folder called AuthComponets.

12) Children Props:

Sometimes it is required to pass functions as props to a child Component. Use children’s props to pass functions to the children’s components. So on an event trigger, they can execute that function and pass back the payload as function arguments.

Reactjs JavaScript best practices:

13) Use template literals:

Template literal is an ES6 feature that makes strings concatenation easy. Use template literals to build strings wherever necessary.

Also, with template literals, you can use variables inside strings using $ notation.

BAD:

const name = "My name is " + myName;

GOOD:

const name = "My name is " + myName;

Also Read: Grid image gallery in CSS, in 5 minutes

14) Use ES6 spread operator:

The JavaScript ES6 spread operator allows copying an object or array into another object or array. Use the spread operator to pass props to a component if it expects the same prop names as the keys in the object.

SYNTAX:

const newArray = [...oldArray, 2, 4]

The newArray now constitutes the elements of the oldArray, 2 and 4.

15) Use logical or ternary operators to render components conditonally:

Use JavaScript’s shortcircuit property to conditionally render components. For example, if you have to render the Post component If isAuth is true, you can use and operator. If the isAuth is true, the execution will move to the Post component and if it’s false, it’ll short circuit and the Component won’t render. The same applies to or operator, the Component on the right side of or operator will only render if isAuth is false.

Furthermore, if you need to render two different components based on if the expression is true or false, you can use the ternary operator.

LogicalOperators:

{isLogin && <LoginForm/> }
{isLogin || <SignupForm/> }

In the above code example, the login form will only be rendered if isLogin is true. And SignupForm will only be rendered if isLogin is false. This is Javascript default behavior and is known as short-circuiting. Short-circuiting simply means that if the LHS of an and operator is true then the right side will be considered and if it’s false, it has no value whether it results in true or false. The same is true with or operator. If LHS is true there is no need to check whether RHS is true or false.

Ternary Operator:

{isLogin : <LoginForm /> ? <SignupForm />}

In the above code example, we use the ternary operator to conditionally render different items. If the isLogin is true, LoginForm will be rendered and if it’s false SignupForm component will be rendered.

16) Use implicit return:

Write arrow functions instead of function declaration and expression to make your code shorter. Also, make use of the arrow function’s implicit return to make your code look nice and shorter.

BAD:

const idArray = userArray.map(user =>{
<strong>return user.id</strong>
})

GOOD:

const idArray = userArray.map(user<strong> =>user.id</strong>);

The above example uses the map method to get the ids of all the users in the user array. The map method returns an array of ids for each user.

17) Use Map function:

Use the map function if you have to render an array of components based on some data. For example, if you have an array of 6 users and you need to render User components for each of them, follow the code given below.

function AllNews(props) {
return (
props.allNews.map(news => {
<NewsItem key="{news.id}" title="{news.title}" details="{news.details}" time="{news.time}">
})
)
}</NewsItem>

In the above code example, we use the map method to return a NewsItem component for each item in the allNews array. This way we render a list of components based on the allNews array.

17) Use Destructuring:

Destructuring allows us to extract an item or items from an array or an object. In Reactjs, a component receives props in the form of an object. So, to get the values out of the received props object use destructuring.

WITH DESTRUCTURING:

function AllNews(props) {
return (
props.allNews.map(news => {
<NewsItem key="{news.id}" title="{news.title}" details="{news.details}" time="{news.time}">
})
)
}</NewsItem>

WITH DESTRUCTURING:

function AllNews(props) {
const {id, title, details, time} = props;
return (
props.allNews.map(news => {
<NewsItem key="{id}" title="{title}" details="{details}" time="{time}">
})
)
}</NewsItem >

18) Use JSX shorthand:

Sometimes, you need to pass a boolean value as a prop and if it’s already defined, you can just pass it. For example

<Form isLogin />

Reactjs best practices to improve app performance:

19) Use memo to improve code performance:

useMemo() hook prevents the component from rendering every time its parent changes or rerenders.

Also, you can wrap functions with useCallback() hook, if you don’t want them to be redeclared on every component render. The callback() hook takes a dependency array. The elements in the dependency array decide when the function should be redeclread. In simple terms, the function will be redeclared if the dependency items change.

20) Use functional components with hooks:

It’s easy to manage the state with functional components with the help of hooks. If you require state management in your component then it’s better to go with functional components. The hooks like useState(), useReducer(), useCallback(), useContext() make working with react state management easy and reduce the amount of code by to a large extent.

21) Do not mix JSX and JS:

JSX is a special syntax used by Reactjs to render components. Never mix JSX with normal JavaScript. Because it’ll make your code less readable and hard to maintain and debug.

22) Avoid unnecessary use of state:

Don’t use state excessively. It’ll decrease the performance of your Reactjs app. For example, if you don’t need to record every keystroke in the text field. Use the useRef() hook to get the value of the input field. It’ll decrease component rendering and save computing resources.

23) Avoid function declearation inside render method:

If you use class-based components, don’t declare functions inside the render method. Instead, declare them as separate methods and call them in the render method. This will keep your render method lean and clean.

Reactjs CSS best practices:

24) Avoid Unnecessary divs:

Don’t use divs as wrappers because if you have a lot of nested components it will result in a div soup. Instead, use Fragment provided by Reactjs to wrap sibling components inside a component.

BAD:

return <div>
<Navigation>
<LoginForm>
</Navigation>
</div>

GOOD:

return <React.Fragment>
<Navigation>
<LoginForm>
</Navigation>
</React.Fragment>

25) CSS in JS:

Don’t use inline CSS with style prop. Also, don’t create a CSS file like a traditional one. But create a file with .module.css. This will ensure that the classes declared inside this file are unique and are not available in the global scope. The .module tells react to add a specific set of characters to the class name to make it unique and inaccessible to other files.

Reactjs security best practices:

26) Add secure authentication:

Most apps need users to log in to access the content. Authentication should be secure to avoid exposing users to hackers. There are many third-party libraries that help with authentication. Some of them are

  1. JSON Web Token (JWT)
  2. OAuth
  3. AuthO
  4. React Router
  5. PassportJs

27) Protect your React App from XSS:

Sanitize your user inputs like search, email, password, and fields to discard malicious and invalid user input. If you don’t discard malicious user input, it might lead to your server and private files getting exposed.

Conclusion:

It’s important to remember these best practices if you want your Reactjs app to be secure and perform well. Although these practices are not mandatory, these are standards for a good Reactjs app. If you find this tutorial useful please leave feedback. Thanks

Newsletter Updates

Enter your email address below to subscribe to our newsletter

5 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Programming & Tech Digest
Programming and Tech innovations delivered straight to your inbox for free.