What are some React anti-patterns?
TL;DR
React anti-patterns are practices that can lead to inefficient, hard-to-maintain, or buggy code. Some common anti-patterns include:
- Mutating state directly instead of using
setState
- Using
componentWillMount
for data fetching - Overusing
componentWillReceiveProps
- Not using keys in lists
- Overusing inline functions in render
- Deeply nested state
Common React anti-patterns
Mutating state directly
Directly mutating the state can lead to unexpected behavior and bugs. Always use setState
to update the state.
Using componentWillMount
for data fetching
componentWillMount
is deprecated and should not be used for data fetching. Use componentDidMount
instead.
Overusing componentWillReceiveProps
componentWillReceiveProps
is deprecated. Use getDerivedStateFromProps
or componentDidUpdate
instead.
Not using keys in lists
Keys help React identify which items have changed, are added, or are removed. Not using keys can lead to inefficient rendering.
Overusing inline functions in render
Defining functions inside the render
method can lead to performance issues because a new function is created on every render.
Deeply nested state
Deeply nested state can make state management complex and error-prone. Flatten the state structure when possible.