Notes on React Hooks
A Hook is a special function that lets you “hook into” React features.
Basically, they are just functions with a fancy name that can do React stuff, like updating state..
Hooks can only be used inside React function components and other hooks.
|useEffect||Add a life cycle event (componentDidMount, ComponentWillMount, ComponentWillUnmount, ComponentDidUpdate..)|
useState()does NOT merge old and new state together (unlike
this.setState). With the
useStatehook you basically overwrite the previous .
this.setStatein a class, updating a state variable always replaces it instead of merging it.
useEffect()is for side effects (data fetching, API calls, manually changing the DOM etc.)
- By default
useEffect()is run on every render (including first render)
- You can change that by passing it an array as second argument, containing parts of state or props that you want to monitor, so that it only runs again if any of that state/prop change. For example
- If you pass an empty array
as second argument, it’ll only run once (on mount and unmount). This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run.
- Effects are declared inside the component so they have access to its props and state. Placing
useEffectinside the component lets us access the state variables (or any props) right from the effect because they’re in scope.
- it combines
componentWillUnmountin a single API (reducing code duplication as a result. previously you’d do the same thing in
- There are two common kinds of side effects in React components: those that don’t require cleanup, and those that do.
- If you return a function inside your Effect, it’ll be treated as cleanup after the effect, i.e. equivalent of
componentWillUnmount. For example, you may want to unsubscribe from something as part of the cleanup
- it is important to clean up so that we don’t introduce a memory leak!
- This function we pass to
useEffectis our effect.
- It cleans up the previous effects before applying the next effects.
- By default
- In the future, React Hooks are not be intended for data fetching in React. Instead, a feature called Suspense will be in charge for it.
If a function’s name starts with ”use” and it calls other Hooks, we say it is a custom Hook.
It’s just a function (with the
useSomething naming convention) that calls other Hooks
Some examples of custom hooks are
useSelector(); // lets you extract data from the Redux store state, using a selector function useDispatch(); // lets you dispatch Actions