Physical Address
Sagipora Sopore Baramulla 193201 Jammu & Kashmir
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
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.
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.
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.
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.
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.
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.
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
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.
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 />
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
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.
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.
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
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.
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.
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.
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.
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 >
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 />
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.
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.
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.
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.
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.
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>
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.
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
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.
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
[…] Also Read: Reactjs best practices 2022, code this not that […]
[…] Reactjs best practices 2022, code this not that April 9, 2022 […]
[…] Reactjs best practices 2022, code this not that April 9, 2022 […]
[…] Reactjs best practices 2022, code this not that April 9, 2022 […]
[…] Reactjs best practices 2022, code this not that April 9, 2022 […]