score:4
sometimes we need a code block where we need to perform some operation right after setstate where we are sure the state is being updated. that is where setstate callback comes into play
for example, there was a scenario where i needed to enable a modal for 2 customers out of 20 customers, for the customers where we enabled it, there was a set of time taking api calls, so it looked like this
async componentdidmount() {
const appconfig = getcustomerconfig();
this.setstate({enablemodal: appconfig?.enablefeatures?.paymentmodal }, async
()=>{
if(this.state.enablemodal){
//make some api call for data needed in poput
}
});
}
enablemodal boolean was required in ui blocks in the render function as well, that's why i did setstate here, otherwise, could've just checked condition once and either called api set or not.
score:33
consider setstate call
this.setstate({ counter: this.state.counter + 1 })
idea
setstate may be called in async function
so you cannot rely on this
. if the above call was made inside a async function this
will refer to state of component at that point of time but we expected this to refer to property inside state at time setstate calling or beginning of async task. and as task was async call thus that property may have changed in time being. thus it is unreliable to use this
keyword to refer to some property of state thus we use callback function whose arguments are previousstate and props which means when async task was done and it was time to update state using setstate call prevstate will refer to state now when setstate has not started yet. ensuring reliability that nextstate would not be corrupted.
wrong code: would lead to corruption of data
this.setstate(
{counter:this.state.counter+1}
);
correct code with setstate having call back function:
this.setstate(
(prevstate,props)=>{
return {counter:prevstate.counter+1};
}
);
thus whenever we need to update our current state to next state based on value possed by property just now and all this is happening in async fashion it is good idea to use setstate as callback function.
i have tried to explain it in codepen here code pen
score:48
the 1. usecase which comes into my mind, is an api
call, which should't go into the render, because it will run for each
state change. and the api call should be only performed on special state change, and not on every render.
changesearchparams = (params) => {
this.setstate({ params }, this.performsearch)
}
performsearch = () => {
api.search(this.state.params, (result) => {
this.setstate({ result })
});
}
hence for any state change, an action can be performed in the render methods body.
very bad practice, because the render
-method should be pure, it means no actions, state changes, api calls, should be performed, just composite your view and return it. actions should be performed on some events only. render is not an event, but componentdidmount
for example.
score:72
this.setstate({
name:'value'
},() => {
console.log(this.state.name);
});
score:291
yes there is, since setstate
works in an asynchronous
way. that means after calling setstate
the this.state
variable is not immediately changed. so if you want to perform an action immediately after setting state on a state variable and then return a result, a callback will be useful
consider the example below
....
changetitle: function changetitle (event) {
this.setstate({ title: event.target.value });
this.validatetitle();
},
validatetitle: function validatetitle () {
if (this.state.title.length === 0) {
this.setstate({ titleerror: "title can't be blank" });
}
},
....
the above code may not work as expected since the title
variable may not have mutated before validation is performed on it. now you may wonder that we can perform the validation in the render()
function itself but it would be better and a cleaner way if we can handle this in the changetitle function itself since that would make your code more organised and understandable
in this case callback is useful
....
changetitle: function changetitle (event) {
this.setstate({ title: event.target.value }, function() {
this.validatetitle();
});
},
validatetitle: function validatetitle () {
if (this.state.title.length === 0) {
this.setstate({ titleerror: "title can't be blank" });
}
},
....
another example will be when you want to dispatch
and action when the state changed. you will want to do it in a callback and not the render()
as it will be called everytime rerendering occurs and hence many such scenarios are possible where you will need callback.
another case is a api call
a case may arise when you need to make an api call based on a particular state change, if you do that in the render method, it will be called on every render onstate
change or because some prop passed down to the child component
changed.
in this case you would want to use a setstate callback
to pass the updated state value to the api call
....
changetitle: function (event) {
this.setstate({ title: event.target.value }, () => this.apicallfunction());
},
apicallfunction: function () {
// call api with the updated value
}
....
Source: stackoverflow.com
Related Query
- When to use React setState callback
- Use callback in setState when referencing the previous state in React
- ESLint: Use callback in setState when referencing the previous state
- React hook: how to use callback in setState
- When to use setState callback argument versus directly passing the value
- How to use callback function in React hooks when value is submitted?
- How does React batch setState when mixing object and callback approach?
- react child component fails to render when calling parent callback with setstate
- using update immutablity helper I get eslint error : Use callback in setState when referencing the previous state
- React - How to use a key to setState on a specific object in an array when modifying a property?
- React Too many re-renders when using setState hook inside callback function
- When I use setState callback to toggleDropdown my dropdown is open after selecting item
- setInterval can't be stopped by clearInterval when use setState in React
- ERROR: use callback in setstate when referencing the previous state
- When to use ES6 class based React components vs. functional ES6 React components?
- How to use `setState` callback on react hooks
- React Context vs React Redux, when should I use each one?
- React functional stateless component, PureComponent, Component; what are the differences and when should we use what?
- How to use callback with useState hook in react
- When should you NOT use React memo?
- When should you use render and shallow in Enzyme / React tests?
- When to use a react framework such as Next or Gatsby vs Create React App
- You should not use Route or withRouter() outside a Router when using react-router 4 and styled-component in react
- When to use functional setState
- React Testing Library: When to use userEvent.click and when to use fireEvent
- How to use absolute path to import custom scss, when using react + webpack?
- React lazy loading - when to use
- When to use React createFragment?
- How to use React links when rendering content with dangerouslySetInnerHtml?
- How to use fetch() API in React to setState
More Query from same tag
- How to use apollo-link-http with apollo-upload-client?
- Trigger a function in another component on click a button from a different component in React
- why TODO list is not working properly in reactjs
- Trouble passing object over as props
- React and Material-UI: Uncaught Invariant Violation: removeComponentAsRefFrom(...)
- How to merge two array of objects with reactjs?
- React js connect to database
- How to use async await with React componentDidMount() method?
- What causes _reduxForm not found, with this.context undefined?
- Dollar symbol ($) in React/ES2015
- Chrome is not rendering div, but MS Edge and development build is rendering as intended using React
- react-scripts build ignores conditional css imports
- How to make autospace after every 4 digit in React
- Cannot Get ReactJS Component to Update
- Dispatching actions from presenational components with regards to Container Component pattern?
- Uncaught TypeError: match is undefined leads to blank page
- How to make sub table <tr> of parent table <tr>?
- Docker compose not properly copying files to run react app
- Uncaught Error: Configuration must contain `projectId`( when using environment variable )
- Unable to create and map through an array using new Array
- How to mock video duration in react testing library?
- React component inside dangerouslySetInnerHTML
- onClick event on stateless components controlling a prop on that Component
- React-resizable - iframe causing resize not to stop when releasing mouse and reaching minConstraints
- How do I add a custom wallet (cdc defi wallet) to web3modal
- React syntax error
- Can't display image from Strapi in ReactJS (frontend)
- CSS id selectors just won't work
- How can I pass a value into a useState
- React Hooks useState() with Object TypeError: Cannot read property 'name' of undefined