All-in-one reference guide for basic and advanced React Hooks, including suggestions for further reading and learning opportunities.
React Hooks were added to React in version 16.8. With the transition from class to functional components, Hooks let you use state and other features within functional components, i.e., without writing a class component.
_useState_
_useEffect_
_useContext_
_useReducer_
_useCallback_
_useMemo_
_useRef_
_useImperativeHandle_
_useLayoutEffect_
_useDebugValue_
This reference guide will discuss all the Hooks natively available in React, but first, let’s start with the basic React Hooks: useState
, useEffect
, and useContext
.
useState
The signature for the useState
Hook is as follows:
const [state, setState] = useState(initialState);
Here, state
and setState
refer to the state value and updater function returned on invoking useState
with some initialState
.
It’s important to note that when your component first renders and invokes useState
, the initialState
is the returned state from useState
.
Also, to update state, the state updater function setState
should be invoked with a new state value, as shown below:
setState(newValue)
By doing this, a new re-render of the component is queued. useState
guarantees that the state
value will always be the most recent after applying updates.
For referential checks, the setState
function’s reference never changes during re-renders.
Why is this important? It’s completely OK to have the updater function in the dependency list of other Hooks, such as useEffect
and useCallback
, as seen below:
useEffect(() => {
setState(5)
}, [setState]) //setState doesn't change, so useEffect is only called on mount.
Note that if the updater function returns the exact same value as the current state, the subsequent re-render is skipped:
The state updater function returned by useState
can be invoked in two ways. The first is by passing a new value directly as an argument:
const [state, setState] = useState(initialStateValue)
// update state as follows
setState(newStateValue)
This is correct and works perfectly in most cases. However, there are cases where a different form of state update is preferred: functional updates.
Here’s the example above revised to use the functional update form:
const [state, setState] = useState(initialStateValue)
// update state as follows
setState((previousStateValue) => newValue)
You pass a function argument to setState
. Internally, React will invoke this function with the previous state as an argument. Whatever is returned from this function is set as the new state.
Let’s take a look at cases where this approach is preferred.
#react #javascript #web-development