As a Front-End Engineer, 4 React Traps And TipsYou Should Know About
1. Don’t forget to remove the listener when the component is Unmounting.
We often need to listen to keyboard events, mouse events, etc. in useEffect
of React
. But we often forget to remove them.
const windowScroll = () => {
console.log('scroll')
}
useEffect(() => {
window.addEventListener("scroll", windowScroll, false)
}, [])
Yes, when we return to this component, the scroll
event will be listened to again.
In other words, we might bind thousands of windowScroll
functions to window
. This will lead to memory leaks and unexpected behaviour of listeners.
Please don’t forget to remove the listener when the component is Unmounting.
const windowScroll = () => {
console.log('scroll')
}
useEffect(() => {
window.addEventListener("scroll", windowScroll, false)
return () => {
window.removeEventListener('scroll', windowScroll, false)
}
}, [])
2. Please use 0 carefully, it is the devil
You may have written a code similar to the one below, what does it display? Or does it show nothing at all?
const App = () => {
const [ list, setList ] = useState([])
return (
list.length && (
<div className="list">
{list.map((name) => {
return <div className="item">{name}</div>
})}
</div>
)
)
}
I don’t think there is anything wrong with this code! But it does show a 0
. Could it be a BUG of React
?
const i = 0
const b = 'fatfish'
console.log(i && b)
I was wrong, it’s not a bug in React
, it's fully compliant with JavaScript
syntax.
To avoid displaying 0
incorrectly, we need to use the following three ways to solve this problem.
// 1. Controlled by specific logic
list.length >= 1 && <Component list={list} />
// 2. Convert list.length to boolean
!!list.length && <Component list={list} />
// 3. Use ternary…