score:3
inside a react event handler (that is, a function called from a react-based onchange={...}
property and the like), multiple calls to setstate
are batched and the component is only re-rendered a single time. so, there's no difference between
handleclick: function() {
this.setstate({fruit1: "apple"});
this.setstate({fruit2: "mango"});
}
and
handleclick: function() {
this.setstate({fruit1: "apple", fruit2: "mango"});
}
however, outside of the react event system, the two calls to setstate
will not be merged unless you wrap them in a function passed to react.addons.batchedupdates
. this is normally not something you have to worry about, but may become an issue if you start setting state in response to asynchronous events (e.g. timers, promises, callbacks, etc). for that reason, i would generally recommend the second form (with the two objects merged into one) over the first.
score:0
here is a detailed explanation of react states and setstate() method.
states (and props) are only two reasons why react re-renders/recalculate the dom. it means if we change state, we are telling react to change the related behaviour of our app.
state is a java-script object with key:value pair. now we may have many states (many key:value pairs) and let's say at certain point only one state is changing. in that case we may use this.setstate() method to change only that specific state.
state = { fruit1: 'mango', fruit2: 'apple' }
let's say we want to update fruit1: 'watermelon'.
here we can say:
this.setstate( {fruit1: 'watermelon'} );
here, we did not say anything about second state (fruit2), so react will merge changed state (fruit1) with old state (fruit2).
while, we can also say:
this.setstate( {fruit1: 'watermelon' ,fruit2:'apple'} );
but it is not necessary.
correct and re-commanded way of setting/changing state:
from react official 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.
so here is a better way to do it: if we are updating the counter or calculating something:
this.setstate((prevstate,props) => {
return {
{ counter: prevstate.counter+1; }
}
score:4
from react documentation:
never mutate this.state directly, as calling setstate() afterwards may replace the mutation you made. treat this.state as if it were immutable. setstate() does not immediately mutate this.state but creates a pending state transition. accessing this.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. setstate() will always trigger a re-render unless conditional rendering logic is implemented in shouldcomponentupdate(). if mutable objects are being used and the logic cannot be implemented in shouldcomponentupdate(), calling setstate() only when the new state differs from the previous state will avoid unnecessary re-renders.
so, use this.setstate({fruit1: “apple”, fruit2: “mango”});
Source: stackoverflow.com
Related Query
- What is the correct way of setting state variables in Reactjs and what is the difference between these approaches?
- What is the correct way of updating state for which the value needed to be a combination of previous state and event
- What is the correct way to update state and render the component?
- ReactJs : What is the proper way of accessing the state data in the root component where the link between React and Redux has been implemented?
- ReactJS: What is the correct way to set a state value as array?
- What is the correct way to handle a key event using useEffect() hook which on the other hand triggers local state changes?
- React Hooks - What is the recommended way to initialize state variables with useState() from props
- What is the correct way to React Hook Fetch Api and store to Redux and retrieve it with Selector immediately?
- Asp.NET Core + ReactJs - What is the correct way to store authentication information?
- what is the correct way to add data array to the array state as well
- What is the correct way to include React in both an application and a private library? (React Invalid Hook Call warning from duplicate React)
- What is the correct way to set state in React
- What is the correct way to push jsx with embedded js variables on to an array
- What is the correct way to set State according to fetch data?
- What is the proper way to fetch data from server with ReactJS and Flux architecture where no Store presented?
- What is the correct way to collect data in react without Re-rendering and Perfomance Issues
- My useMemo useCallback does not reduce the number of render. What is the correct way to use useMemo and useCallback?
- What is the right way to manage synthetic events using hooks and update the state from event handlers?
- What is the correct way of creating a Closure or IIFE for handling an onclick event in ReactJS
- What is the correct way to do an async action using redux observable and firebase?
- What is the difference between state and props in React?
- What is the best way to add a value to an array in state
- What is the difference between Reactjs and Rxjs?
- React - What is the best way to handle login and authentication?
- What is the correct way of adding a dependency to react in your package.json for a react component
- What is the correct order of execution of useEffect in React parent and child components?
- Correct way of Creating multiple stores with mobx and injecting it into to a Component - ReactJs
- ReactJS : What is the best way to give keys in array element
- ReactJS - What is difference between component state and class variable?
- Correct way to throttle HTTP calls based on state in redux and react
More Query from same tag
- How do I calculate the contents of the input bar? - ReactJS
- Sign out and always pop up asking for account google firebase
- Shopify-Buy-SDK Get Raw Product Data
- how do i call another function outside my class
- how to call onStart function in react-countdown?
- ReactJS, passing data between siblings
- How to make props.relay.setVariables update my data?
- Having a problem with PrimeReact Dropdown
- useEffect() triggers components re-render in one function but not in the other one. Both function DO change state. What am I missing?
- file input files not read onChange on mobile
- How to show a Modal once onShowMoreClick is clicked?
- React native-fbsdk unknown issue?
- Is there any way to dynamically add JSON fields in Javascript?
- Graphql error : "syntax error before: \"\\\"variables\\\"\""
- Get live updated data with ajax in a react component
- filtering through an array of JSON objects by UI
- Handling array length in React
- How to retain props or state in a react component?
- Get request axios React js useEffect is not working (Cannot find module './undefined')
- Learning React: how to useRef in custom component?
- How could I change mui x-data-grid sorting icon and menu icon color
- ReactJS: Change current Image being displayed using prev and next buttons
- Dynamic object keys... Cannot create property on string
- How does object spread notation transform react redux props?
- 'UserContextProvider' is not defined
- How to pass parameters from a button in REACTJS?
- TypeError: props.history.listen is not a function. I am using ReactJS
- Firebase URL rewriting to both functions and destinations
- React and Firebase: adding date to database causes listener to trigger twice?
- Showing the error "cannot find the module 'undefined'" when iam trying to give the location of image using props