Coding Practices in React

Pooja Mehta
The Startup
Published in
3 min readSep 6, 2020

--

Conventionally organised desk - RetroSupply on Unsplash

Let’s first be clear that this is not a post with all the best coding practices in React. It’s a post about some of the practices that I have learned over years of my experience while working with React. They might not be the best ones, but they surely add quality to the code written.

Deciding the component type — functional or classical?

With the introduction of hooks in React, I often find people struggling over the point where they cannot decide whether they should create a functional component or classical component? If you are not familiar with Hooks yet, then you check this.👩‍💻

This depends completely on your requirement — if your component has fewer or no states with not much involvement of component lifecycle methods, then you can choose to create a functional component else you can choose a normal classical component. There are no strict rules to make this decision.

Organising code in component

This is strictly a personal choice I feel, one can follow any standard way to write code in their component. The main idea here is to follow a consistent approach for writing code in all components.

It’s not what we do once in a while that shapes our lives. It’s what we do consistently. — Anthony Robbins

Organising your imports

One can follow any standard order to manage their imports in the component, I have listed the import sequence order which I follow for managing imports in my components:

  • Imports from ‘react’ or ‘react-dom
  • 3rd party library imports like ‘lodash’ or ‘clsx
  • Import of components from my ‘ui-kit’
  • Import context providers
  • Import of utility methods, helper classes and constants
  • Import of scss/css files
import React, { useState } from 'react'; import clsx from 'clsx'; 
import * as _ from 'lodash';
import Button from 'ui-kit/Button';import { AppContext } from './App.js'; import { CONSTANTS } from "./utility/constants";
import { convertToJSON } from './utility/helper';
import './scss/app.scss';

Organising component state and variables

In classical components we define state variables for the component in the constructor and in functional components we define them at the beginning of the functional component. It is the standard way but we can take care of some additional points while doing that:

  • Organise all state variables based on their value types
  • Define context consumer variables
  • Define refs
  • Other local variables
const [isActive, setIsActive] = useState(false);
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
const [isScreenLoading, setIsScreenLoading] = useState(true);
const [selectedIndex, setSelectedIndex] = useState(-1);
const [message, setMessage] = useState("Hello World!");
const [rows, setRows] = useState([]);
const appContext = useContext(AppContext);const buttonRef = useRef(null);
const inputRef = useRef(null);
const pathID = props.match.params.id;

Organising methods in component

Everybody follows different techniques for managing methods in their component. But we can surely follow some conventions to make our component code easily understandable to any developer.

  • Define all the API call invocation methods
  • Define all event handlers like button click, text change, error handlers etc
  • Define helper methods returning either JSX or data required for render
  • Define lifecycle methods like componentDidMount() or hooks like useEffect
const fetchInitialData = (bot, channel) => {
const endpoint = `/v1/todos`;
const headers = {
"Accept": "application/json",
"Content-type": "application/json"
};
fetch(endpoint, headers).then(response => response.json()).then(response => setRows(response.data));
}
const statusChangeHandler = (status) => {
setIsActive(status);
}
const customScroll = (event) => {
// custom scroll listener
}
const getPopupMessage = () => {
return `This message is received from user ${pathID}`;
}
useEffect(() => {
// register listener
window.addEventListener("scroll", customScroll);
return () => {
// unregister listener
window.removeEventListener("scroll", customScroll);
}
}, []);

These are some of the practices that I follow to make the code in all my components consistent. As people say, there is no such thing as “perfect” code, there is always a chance for “better” code. Learn to code better everyday!🎉 Happy Coding! 🙂

--

--