score:3
This callback is really messy. Just use async await instead:
async openAddBoardModal(){
await this.setState({ boardAddModalShow: true });
console.log(this.state.boardAddModalShow);
}
score:-2
this.setState({
isMonthFee: !this.state.isMonthFee,
}, () => {
console.log(this.state.isMonthFee);
})
score:-2
Yes because setState is an asynchronous function. The best way to set state right after you write set state is by using Object.assign like this: For eg you want to set a property isValid to true, do it like this
Object.assign(this.state, { isValid: true })
You can access updated state just after writing this line.
score:-2
when i was running the code and checking my output at console it showing the that it is undefined. After i search around and find something that worked for me.
componentDidUpdate(){}
I added this method in my code after constructor(). check out the life cycle of react native workflow.
score:1
setState()
is asynchronous. The best way to verify if the state is updating would be in the componentDidUpdate()
and not to put a console.log(this.state.boardAddModalShow)
after this.setState({ boardAddModalShow: true })
.
according to React Docs
Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately
score:1
According to React Docs
React does not guarantee that the state changes are applied immediately. This makes reading this.state right after calling setState() a potential
pitfall
and can potentially return theexisting
value due toasync
nature . Instead, usecomponentDidUpdate
or asetState
callback that is executed right after setState operation is successful.Generally we recommend usingcomponentDidUpdate()
for such logic instead.
Example:
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
constructor() {
super();
this.state = {
counter: 1
};
}
componentDidUpdate() {
console.log("componentDidUpdate fired");
console.log("STATE", this.state);
}
updateState = () => {
this.setState(
(state, props) => {
return { counter: state.counter + 1 };
});
};
render() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={this.updateState}>Update State</button>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
score:2
If you want to track the state is updating or not then the another way of doing the same thing is
_stateUpdated(){
console.log(this.state. boardAddModalShow);
}
openAddBoardModal(){
this.setState(
{boardAddModalShow: true},
this._stateUpdated.bind(this)
);
}
This way you can call the method "_stateUpdated" every time you try to update the state for debugging.
score:2
Although there are many good answers, if someone lands on this page searching for alternative to useState
for implementing UI components like Navigation drawers which should be opened or closed based on user input, this answer would be helpful.
Though useState
seems handy approach, the state is not set immediately and thus, your website or app looks laggy... And if your page is large enough, react is going to take long time to compute what all should be updated upon state change...
My suggestion is to use refs and directly manipulate the DOM when you want UI to change immediately in response to user action.
Using state for this purspose is really a bad idea in case of react.
score:2
The above solutions don't work for useState hooks. One can use the below code
setState((prevState) => {
console.log(boardAddModalShow)
// call functions
// fetch state using prevState and update
return { ...prevState, boardAddModalShow: true }
});
score:3
Think of
setState()
as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.
Check this for more information.
In your case you have sent a request to update the state. It takes time for React to respond. If you try to immediately console.log
the state, you will get the old value.
score:8
setState()
does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState()
a potential pitfall. Instead, use componentDidUpdate
or a setState
callback (setState(updater, callback)
), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.
setState()
will always lead to a re-render unless shouldComponentUpdate()
returns false. If mutable objects are being used and conditional rendering logic cannot be implemented in shouldComponentUpdate()
, calling setState()
only when the new state differs from the previous state will avoid unnecessary re-renders.
The first argument is an updater function with the signature:
(state, props) => stateChange
state
is a reference to the component state at the time the change is being applied. It should not be directly mutated. Instead, changes should be represented by building a new object based on the input from state and props. For instance, suppose we wanted to increment a value in state by props.step:
this.setState((state, props) => {
return {counter: state.counter + props.step};
});
score:13
For anyone trying to do this with hooks, you need useEffect
.
function App() {
const [x, setX] = useState(5)
const [y, setY] = useState(15)
console.log("Element is rendered:", x, y)
// setting y does not trigger the effect
// the second argument is an array of dependencies
useEffect(() => console.log("re-render because x changed:", x), [x])
function handleXClick() {
console.log("x before setting:", x)
setX(10)
console.log("x in *line* after setting:", x)
}
return <>
<div> x is {x}. </div>
<button onClick={handleXClick}> set x to 10</button>
<div> y is {y}. </div>
<button onClick={() => setY(20)}> set y to 20</button>
</>
}
Output:
Element is rendered: 5 15
re-render because x changed: 5
(press x button)
x before setting: 5
x in *line* after setting: 5
Element is rendered: 10 15
re-render because x changed: 10
(press y button)
Element is rendered: 10 20
score:14
Since setSatate is a asynchronous function so you need to console the state as a callback like this.
openAddBoardModal(){
this.setState({ boardAddModalShow: true }, () => {
console.log(this.state.boardAddModalShow)
});
}
score:52
Fortunately setState()
takes a callback. And this is where we get updated state.
Consider this example.
this.setState({ name: "myname" }, () => {
//callback
console.log(this.state.name) // myname
});
So When callback fires, this.state is the updated state.
You can get mutated/updated
data in callback.
score:205
Your state needs some time to mutate, and since console.log(this.state.boardAddModalShow)
executes before the state mutates, you get the previous value as output. So you need to write the console in the callback to the setState
function
openAddBoardModal() {
this.setState({ boardAddModalShow: true }, function () {
console.log(this.state.boardAddModalShow);
});
}
setState
is asynchronous. It means you can’t call it on one line and assume the state has changed on the next.
According to React docs
setState()
does not immediately mutatethis.state
but creates a pending state transition. Accessingthis.state
after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.
Why would they make setState
async
This is because
setState
alters the state and causes rerendering. This can be an expensive operation and making it synchronous might leave the browser unresponsive.Thus the
setState
calls are asynchronous as well as batched for better UI experience and performance.
Source: stackoverflow.com
Related Query
- setState doesn't update the state immediately
- setState doesnt seem to update the state
- How do I update the state (using ReactJS) if I should not call setState in componentWillUpdate?
- Force a re-render (update the state and update the DOM) immediately with react.js
- I need to execute a function that will update the state right after using setState hook, but state inside function is empty?
- setState does not update state immediately inside setInterval
- ReactJS - SetState does not update the state when the state variable is a number
- React setState componentDidUpdate React limits the number of .. when trying to update the state based on updated state
- How to update the state immediately in React functional component?
- ReactJS best way to update the state with asynchronous setState
- React Hooks: updating state using useState does not update the state immediately
- React/JavaScript, can someone explain why setState doesn't seem to correctly update the state during the function?
- React setState doesn't update the state after submitting input form
- React setState doesnt update state while changing an image
- setState doesn't update the state array
- using update immutablity helper I get eslint error : Use callback in setState when referencing the previous state
- Radio button onChange function doesnt update the state of app - React
- Checkbox doesnt update on react on child even if the parent state update?
- React useState and onSubmit form doesn't update the state immediately - validation best practice
- React text state doesnt update immediately
- React setState and use the value to update another state
- React-UseState hook-> state update does not re-render the page immediately
- Image with public URL from GCS won't display immediately after state update but works after refreshing the page
- setstate doesnt set the state
- React setState doesnt update data immediately
- How can I update multiple state variables using setState while using the spread operator?
- How can I make sure that the state gets update immediately after i refresh the page?
- How to update a state array multiple times faster than the setState without overwriting?
- reducer doesnt update the state
- How can I update the parent's state in React?
More Query from same tag
- Absolute path doesn't work, "Can't resolve"
- How to style a React Component in the HTML
- ReactJS set state of another class through props callback
- Conditional code snippets with React showing both cases
- Reactjs - Cannot read the property of undefined
- Checkboxes not checking in React drop down menu?
- I can not collect data from my json - React
- Setting MDX Component Props in NextJS
- How to solve the issue of a text cursor in a text input being automatically placed at the end of the input after a typed character has been inserted?
- Handling UI state with Flux and React
- How would I sort a prop of an array of objects nondestructively Reactjs?
- Using a checkbox with Material UI to change the boolean value of an attribute within redux
- How to access a value of the array present in useEffect, in the return function of the functional component in react.js?
- How safe is front end with react and redux?
- "Cannot use import statement outside a module" error when importing react-hook-mousetrap in Next.js
- react-select: Prevent long text from overlapping
- setRTLTextPlugin cannot be called multiple times - reactjs
- Accessing state value from StyleSheet.create in ReactNative
- How to avoid dangerouslySetInnerHTML?
- React AntD - Select resetting after filtering
- react class based component vs classes in java
- How do I get the TOTAL price from the updated state? (reactjs)
- How to group values from an array of objects by same values with javascript?
- How to conditionally route components in React?
- Get Value of array name in react js in functional componet
- Passing data from parent component to child component on button click
- Uploading images to state in react
- Writing a shorter form of the if statements in this useEffect
- Do calculations with users input
- useFetch hook with typescript and axios