Refactoring React Components
Introduction
This document will explain the general steps in refactoring a React file
Prerequisites
Make sure you have eslint vs code extension installed
Make sure you have format on save configured (link setup doc)
Steps to Refactor
Save the file to auto format and run eslint, prettier, and sort-imports
Resolve any eslint warnings (unused vars, nested ternaries, complex functions, etc.)
Reduce code footprint
Destructure the props in the argument of the function instead of accessing like
props.name
// good function UserDetail({ name, age, }) { return ( <p>Name: {name} Age: {age}</p> ) } // bad function UserDetail(props) { return ( <p>Name: {props.name} Age: {props.age}</p> ) }
Remove open ended ternaries ex. empty string →
var ? <something> : ''
orvar ? <something> : null
and replace them with the&&
operatorvar && <something>
When possible reduce the logic done in a useEffect by calling to functions outside of the useEffect.
Identify repeated code in functions where a cost can be created and reused. This is common in ternary operators where both sides are returning a whole block of code with one difference.
Identify and create components out of code blocks that could fully function on their own. They do not need to be refactored all the way to fully reusable across the while application/api until we identify it as needed, but it should be reused within the file that's being refactored if needed.
We want to make sure each file is only doing what its set out to do. A table of information does not need logic for a legend modal. The legend modal should be its own component and imported
Order the declaration of variables and functions in the below order
Imports
Constructor
Non state hooks (useDispatch etc.)
State hooks (useState)
useEffects
There may be times when a function needs to be created before a useEffect when used in the useEffect, this is fine.
Functions
JSX return value
Simplify existing logic if needed
Create new components and import them