Hooks are a major part of modern React and for that I created a video series explaining the most important 10 React Hooks in details. Understanding these hook will really help you to level up your react game.
Below are the 10 major react hooks explained with examples.
Enjoy! ✌️
0. The Rules of Hooks
- Hooks should be called at a top level of a component. Do not call hooks inside conditions, loops or nested functions.
- Hooks are only usable in react
functional components
andcustom hooks
. Do not use hooks in class components.
1. useState
The useState hook
let's you add state variable to a component.
2. useEffect
The useEffect hook
is use to synchronize a component with an external system (also know as side effects). Good examples of side effects are, data fetching
, subscriptions/event listeners
and timer/intervals
.
3. useCallback
The useCallback hook
helps you to optimize functions between re-renders.
4. useMemo
The useMemo hook
is used in a similar way as the useCallback hook, only that useMemo is used to optimize values while useCallback is used to optimize functions.
5. useRef
The useRef hook
is used to create a reference to a value(or element). The ref
persists across renders and does not cause the component to re-render when its value changes.
6. useReducer
The useReducer hook
is an alternative to useState hook. It is often favored for more complex state management scenarios.
7. useContext
The useContext hook
is used to consume a context. Context in React is a way to pass data through the component tree without having to pass props manually at every level. useContext hook together with the react context are used to manage some form of global state, e.g a user/auth state.
8. useId
The useId hook
is used to generate unique IDs that can be passed to accessibility attributes.
9. use (new)
The use hook
lets you read the value of a resource like a Promise or context. This hook is unique because it does not follow all the rules of hooks. You can call it inside loops or even conditions like in if else
statements.
10. useTransition
The useTransition hook
lets you update the state without blocking the UI.