When we might need useState functional updates and how to use them
When we need to hold any state, useState
is the most common solution in React nowadays. It returns the current state value and a method to update it:
const [state, setState] = useState(initialValue);
Most of the time, setState
is used in a straightforward way when we call it with our desired state value passed as an argument: setState(newState)
.
It’s simple and sufficient in most cases.
However, it’s not the only way to modify the state with setState
. In the React documentation about useState
, there is a paragraph explaining a functional way to update the state: functional updates.
Basically, they let you pass a function to setState
instead of a value. That function will receive the current state as the first parameter and the returned value will become a new state, like this:
setState(currentState => {
const newState = modify(currentState);
return newState;
});
If we are operating in a synchronous environment, most of the time, a regular setState
will be sufficient. It starts to get complicated when multiple pieces of the application share the state and we have to work with asynchronous functions (e.g. when making API requests).
In other words, when we call an asynchronous function and reach the point of calling setState
, other variables that we calculate a new state from might already be outdated.
Article covers: How native is react native?, React Native vs (Ionic, Cordova), Similarities and difference between React Native and Native App Development.
In this article, you will learn what are hooks in React JS? and when to use react hooks? Also, we will see the react hooks example.
In this post, I will share my own point of view about React Hooks, and as the title of this post implies, I am not a big fan.
React hooks tutorial for beginners, learn React hooks step by step: Introduction, useState Hook, useState with previous state, useState with object, useState with array, useEffect Hook, useEffect after render, Conditionally run effects, Run effects only once, useEffect with cleanup, useEffect with incorrect dependency, Fetching data with useEffect, useContext Hook, useReducer Hook, useReducer, Multiple useReducers, useReducer with useContext, Fetching data with useReducer, useState vs useReducer, useCallback Hook, useMemo Hook, useRef Hook
In this article, we will take a look at useEffect React hook to fetch data from an API. We will create a sample React application to pull data from the provider and use it in our application.