𝗥𝗲𝗮𝗰𝘁 𝗝𝘀 𝗨𝘀𝗲𝗦𝘁𝗮𝘁𝗲 𝗔𝗻𝘁𝗶𝗽𝗮𝘁𝘁𝗲𝗿𝗻𝘀
Writing clean React code requires smart state management. Bad state patterns lead to bugs and complex code.
Avoid these four common mistakes:
- Group related data
Do not create separate state hooks for values that change together.
Instead of:
- const [x, setX] = useState(0);
- const [y, setY] = useState(0);
Use an object:
- const [position, setPosition] = useState({ x: 0, y: 0 });
This keeps your updates clean and organized.
- Avoid conflicting states
When multiple booleans track the same process, you create bugs.
Instead of having:
- isSubmitting
- isSubmit
Use a single status string:
- status: 'TYPING'
- status: 'SUBMITTING'
- status: 'SUBMITTED'
Derive your UI logic from this single source of truth.
- Remove redundant state
If you can calculate a value during render, do not put it in state.
Do not store:
- firstName
- lastName
- fullName
Just store the first and last names. Calculate the full name on the fly:
- const fullName = firstName + " " + lastName;
Also, never store props in state. State only initializes once. If your prop changes, the state will not update. Use the prop directly.
- Stop duplicating data
Do not store the same data in two different states.
If you have a list of tasks and a selected task, do not store the whole task object in both places. This makes updates difficult.
Instead:
- Store the list of tasks.
- Store only the selectedTaskId.
- Find the task from the list using that ID during render.
This ensures your selected task always matches the latest data in your list.
Source: https://dev.to/kkr0423/reactjs-usestate-antipatterns-58i9