An Introduction to react hooks rules
Aman Kumar Singh
Posted on February 25, 2021
Through this article i will try to explain react hooks in beginner friendly manner hope you enjoy and learn through this article.
Let's try to understand in what ways you can use hooks
Rules of Hooks
Only use hook at the top level
Never call hooks inside
- 1 .loops
- 2 .conditions
- 3 .nested functions
On contrary always use at the top level of your react function. This is necessary to ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.
Only hooks from react function
- ✅ Call Hooks from React function components.
- ✅ Call Hooks from custom Hooks
Now lets see some example of what we discussed above
function Form() {
// 1. Use the name state variable
const [name, setName] = useState('Mary');
// 2. Use an effect for persisting the form
useEffect(function persistForm() {
localStorage.setItem('formData', name);
});
// 3. Use the surname state variable
const [surname, setSurname] = useState('Poppins');
// 4. Use an effect for updating the title
useEffect(function updateTitle() {
document.title = name + ' ' + surname;
});
// ...
}
Order of execution
useState('Mary') // 1. Initialize the name state variable with 'Mary'
useEffect(persistForm) // 2. Add an effect for persisting the form
useState('Poppins') // 3. Initialize the surname state variable with 'Poppins'
useEffect(updateTitle) // 4. Add an effect for updating the title
Example of what we cannot do
// 🔴 We're breaking the first rule by using a Hook in a condition
if (name !== '') {
useEffect(function persistForm() {
localStorage.setItem('formData', name);
});
}
//
useState('Mary') // 1. Read the name state variable (argument is ignored)
// useEffect(persistForm) // 🔴 This Hook was skipped!
useState('Poppins') // 🔴 2 (but was 3). Fail to read the surname state variable
useEffect(updateTitle) // 🔴 3 (but was 4). Fail to replace the effect
Instead this is what we can do
useEffect(function persistForm() {
// 👍 We're not breaking the first rule anymore
if (name !== '') {
localStorage.setItem('formData', name);
}
});
Conclusion
I will be writing articles explaining each hooks provided by react in upcoming articles please follow to stay connected.
For more detailed explanation please visit
Posted on February 25, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.