【React】React Hooks
The actual contents comes from Epic React’s React Hooks Workshop.
If you have interests, you can check Epic React by Kent C. Dodds.
useState
useState is a function that accepts a single argument which is the initial state.
useState returns a pair of values.
The first of the pair is the state value and the second is a function we can call to update the state.
What is State?
State can be defined as: data that changes over time.
Lazy State Initialization
useState allows us to pass a function instead of the actual value, and then it will only call that function to get the state value when the component is rendered the first time.
useEffect
useEffect is a built-in hook that allows us to run some custom code after component render and re-render.
It accepts a callback function which React will call after browser painting.
But there are various reasons a component can be re-rendered like when a parent component in the application tree gets re-rendered.
So we need a way to prevent side effects run frequently.
Dependency Array
useEffect allows us to pass a second argument called the “dependency array” which signals to React that your effect callback function should be called when (and only when) those dependencies change.
useCallback
We pass React a function and React gives that same function back to us, but with a catch.
On subsequent renders, if the elements in the dependency list are unchanged, React will give us the same function it gave us last time.
So while we still create a new function every render (to pass to useCallback), React only gives us the new one if the dependency list changes.
useMemo
useMemo is similar to useCallback except it allows you to apply memoization to any value type (not just functions).
It allows us to put that calculation behind a function which is only called when the dependencies change.
As long as those dependencies does not change, the result of our function will be the same as the last time the function was called.
memo
React.memo make our component will not re-render simply because its parent re-rendered.
React.memo also accepts a second argument which is a custom compare function that allows us to compare the props and return true if rendering the component again is unnecessary and false if it is necessary.