Class 31: Hooks API - mwilkin-401-advanced-javascript/bend-javascript-401d2 GitHub Wiki
Hooks are functions that let you “hook into” React state and lifecycle features from function components.
Hooks allow use of state and other React features without writing a class.
* It is similar to this.setState in a class, except it doesn’t merge the old and new state together.
React provided a few built-in Hooks -> useState
, useEffect
,
* Custom Hooks can be created to reuse stateful behavior between different components.
* Effects are declared inside the component so they have access to its props and state.
By default, React runs the effects after every render — including the first render.
Hooks let you organize side effects in a component by what pieces are related rather than forcing a split based on lifecycle methods.
Hook Rules:
- Only call Hooks at the top level.
- Don’t call Hooks inside loops, conditions, or nested functions.
-
- Only call Hooks from React function components.
-
-
- Don’t call Hooks from regular JavaScript functions.
Custom Hooks allow reuse of some stateful logic (not the state itself) between components without adding more components to your tree.
* Each call to a Hook has a completely isolated state
The State Hook can be used to provide local state to function-based components.
* Returns with the state you provided and a function to change the state.
The Effect Hook lets you perform side effects in function components.
* e.g. Data fetching, setting up a subscription, and manually changing the DOM in React components
There are two common kinds of side effects in React components:
* those that don’t require cleanup
* those that do
The Hook lifecycle
- As long as the component is not unmounted, re-renders do not create new hook-related functions and objects, such as the setState callback from useState. React smartly use the same reference for every re-render. The same applies for useEffect.
- When the component is unmounted, all hook-related functions and objects are discarded.
- If the component is mounted again, the hook will start from scratch, functions and objects will not be the same from before.