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
Top comments (2)
Hello, thanks for sharing. π
If you would like to add syntax coloring to your code:
Markdown - how to make blocks of React code (syntax highlighting - github, dev.to)
I personally struggeled with this.
At the beginning of the src code line after 3 x the grave accent sign, we need to add jsx.
This is React code sample:
Thanks for sharing I will do that