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.
Hooks | Purpose |
---|---|
useEffect | Add a life cycle event (componentDidMount, ComponentWillMount, ComponentWillUnmount, ComponentDidUpdate..) |
useState | Add state |
useState()
does NOT merge old and new state together (unlike this.setState
). With the useState
hook you basically overwrite the previous .this.setState
in 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.)useEffect()
is run on every render (including first render)[count]
[]
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.useEffect
inside the component lets us access the state variables (or any props) right from the effect because they’re in scope.componentDidMount
, componentDidUpdate
, and componentWillUnmount
in a single API (reducing code duplication as a result. previously you’d do the same thing in componentDidMount
and componentDidUpdate
)componentWillUnmount
. For example, you may want to unsubscribe from something as part of the cleanupuseEffect
is our effect.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 react-redux
hooks:
1useSelector(); // lets you extract data from the Redux store state, using a selector function
2useDispatch(); // lets you dispatch Actions