Hooks are the powerful functions in React that helps us to leverage the lifecycle features and share states. Since, the functional component has been the recommended way of writing in React, we are using Hooks as much as possible. Certainly, with every power that it gives, we are definitely going to be ambush it at some point. Let's see the most common pitfalls and the mistakes we do as a developer while using React Hooks:
Creating multiple states and using in UseEffect:
Suppose there are multiple states that we are defining using useState. Let's say a first number and a second number.
const [firstNumber, setFirstNumber] = useState(0);
const [secondNumber, setSecondNumber] = useState(0);
Let us suppose that a second number is dependent on a first number. Let's say we manipulate the first number.
const changeFirstNumber = () => {
setFirstNumber(10)
}
useEffect(() => {if(firstNumber) {
setSecondNumber(firstNumber * 10)
}
}, [firstNumber])
Do you think we even need "useEffect" here to manipulate the second number which let's say depends on first number? 🤔 Do we even need a separate state here for "secondNumber"?
The answer is no. We don't need a separate state for second Number in case it is only depended on first Number. Since whenever, state changes, the functional component starts to execute itself from the beginning, so we don't need another state to change the second number.
const [firstNumber, setFirstNumber] = useState(0);
const secondNumber = firstNumber * 10;