Why Hooks
Syntax
In a hook -> A state variable can be ->
- A number
- A string
- Boolean
- Object
- Array
If we have use dan object as set state and modified a part of it and then some other part it doesn't merge them and update but updates them independently and so they are rendered on screen as different entities so to rule that out we us ethe spread operator to give the whole object value first and then modify a part(s) of it.
Hooks with Arrays
Things to remember while dealing with hooks
useEffect
It is basically whenever the component renders or update in rendering on screen this useEffect() gets triggered and what we define under this is what function we want to trigger. Here we have defined an arrow function.
In a class component
A simple condition will help us to not re-render unnecessarily.
Similarly with Functional Components
We can use useEffect() to do the same by adding the state or prop to be checked if it has updated or not if it's not then useEffect() isn't executed.
How to mimic ComponentWillUnmount() in a Functional Component
With the help of removeEventListener()
Tick in Hooks
To mention the state variable that we need to re-render needs to be mentioned in the dependency array (a.k.a the array that is passed to useEffect()). This is how we re-render specific state variables.
OR
By using state variable's prevState to update the new state and re-render it on screen.
Multiple useEffect to group the data
This groups relevant data together and use multiple useEffect -> Notice how we have a state variable declared and a corresponding useEffect for it. This solve the problem of "relevant data far apart" in CLass Components
Context
Defining context in parent component
Using context in child component
Shortcut for using context