ReactJS Code Mistakes & Power Enhancements
π«βοΈ ReactJS Code Mistakes & Power Enhancements Every Developer Should Know! β‘π‘
ReactJS is a developerβs best friend β fast, efficient, and flexible. But even pros can slip up! π€¦ββοΈ Whether youβre a beginner or a seasoned dev, avoiding common pitfalls and using best practices can supercharge your React apps π.
Letβs dive into some React mistakes you should avoid β and some enhancements you must adopt! π§ πͺ
1οΈβ£ β Mutating State Directly
π¨ Mistake:
const [user, setUser] = useState({ name: 'John', age: 30 });
user.age = 31; // β Direct mutation
setUser(user); // Won't re-render!
β Enhancement:
setUser((prev) => ({ ...prev, age: 31 })); // βοΈ Immutable update
π Why it matters:
React relies on immutability to detect changes. Mutating state directly can lead to stale UI and bugs that are very hard to track!
2οΈβ£ π Overusing useEffect
π¨ Mistake:
useEffect(() => {
fetchData();
}, [data]); // β Causes infinite loop
β Enhancement:
useEffect(() => {
fetchData();
}, []); // βοΈ Fetch once on mount
π‘ Pro Tip:
Use useEffect only when needed. Itβs not a dumping ground for all logic β itβs meant for side effects like fetching data or setting up subscriptions.
3οΈβ£ π Missing Keys in Lists
π¨ Mistake:
{items.map((item) => (
<div>{item.name}</div> // β No key
))}
β Enhancement:
{items.map((item) => (
<div key={item.id}>{item.name}</div> // βοΈ Unique key
))}
π― Why it matters:
React uses keys to efficiently update the DOM. Without them, your app might behave unpredictably π΅βπ«.
4οΈβ£ π§± Too Many Props Drilling
π¨ Mistake:
Passing props from parent β child β grandchild β β¦ π€―
<Grandparent user={user} />
All the way down to:
<Child user={user} />
β Enhancement:
β Use Context API or State Management like Redux, Zustand, or Jotai.
const UserContext = createContext();
function App() {
return (
<UserContext.Provider value={user}>
<ComponentTree />
</UserContext.Provider>
);
}
function Child() {
const user = useContext(UserContext);
return <div>{user.name}</div>;
}
π Bonus Tip:
π Use useContext wisely β too many re-renders can occur if not optimized with memoization.
5οΈβ£ π§ Forgetting Memoization (Re-Renders Everywhere!)
π¨ Mistake:
const handleClick = () => { console.log("Clicked"); };
Used in child props β causes child to re-render on every parent render.
β Enhancement:
const handleClick = useCallback(() => {
console.log("Clicked");
}, []);
Or memoize the child:
const Child = React.memo(({ handleClick }) => {
return <button onClick={handleClick}>Click</button>;
});
π§ Why it matters:
React compares references. Without useCallback, new functions are created on every render β unnecessary re-renders.
6οΈβ£ π§ͺ Ignoring Component Reusability
π¨ Mistake:
Copy-pasting the same UI blocks everywhere π
β Enhancement:
Break code into reusable, composable components:
const Button = ({ label, onClick }) => (
<button onClick={onClick}>{label}</button>
);
// Use it anywhere!
<Button label="Submit" onClick={handleSubmit} />
π§± Bonus Tip:
Build a small design system for reusable UI!
7οΈβ£ π¦ Not Handling Loading & Errors
π¨ Mistake:
const [data, setData] = useState();
useEffect(() => {
fetchData().then(setData);
}, []);
No loading or error state π¬
β Enhancement:
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetchData()
.then((res) => setData(res))
.catch(setError)
.finally(() => setLoading(false));
}, []);
π Result:
β Smooth UX with loading spinners and error fallbacks!
8οΈβ£ π§Ή Not Cleaning Up Side Effects
π¨ Mistake:
useEffect(() => {
const interval = setInterval(() => { console.log("Tick"); }, 1000);
}, []);
No cleanup! Leads to memory leaks π₯
β Enhancement:
useEffect(() => {
const interval = setInterval(() => { console.log("Tick"); }, 1000);
return () => clearInterval(interval); // βοΈ Clean up
}, []);
9οΈβ£ πͺ Not Using PropTypes or TypeScript
π¨ Mistake:
const MyComponent = ({ name }) => <div>{name}</div>;
// No validation!
β Enhancement:
import PropTypes from 'prop-types';
MyComponent.propTypes = {
name: PropTypes.string.isRequired,
};
Or use TypeScript:
type MyComponentProps = {
name: string;
};
const MyComponent = ({ name }: MyComponentProps) => <div>{name}</div>;
π Why?
It saves hours of debugging and makes your components self-documenting!
π Wrapping Up!
Mastering React is not just about writing code β itβs about writing smart, clean, and maintainable code π§ββοΈπ»
π₯ Hereβs a quick recap:
β
Keep state immutable
β
Donβt abuse useEffect
β
Always add keys in lists
β
Avoid props drilling
β
Use memoization
β
Reuse components
β
Handle loading & errors
β
Clean up effects
β
Use PropTypes or TypeScript
β¨ Letβs Level Up Together!
If this helped you, consider bookmarking π and sharing with your dev friends π¨βπ»π©βπ»
π£ Let me know your worst React mistake in the comments! Letβs grow together π¬π
© Lakhveer Singh Rajput - Blogs. All Rights Reserved.