Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React setState + Where does 'prevState' come from?

People also ask

How do I get prevState on setState?

prevState() is the same as the setState but the only difference between them is that if we want to change the state of a component based on the previous state of that component, we use this. setState() , which provides us the prevState . Let's check an example of a counter app.

Does setState cause re render?

setState() will always lead to a re-render unless shouldComponentUpdate() returns false . To avoid unnecessary renders, calling setState() only when the new state differs from the previous state makes sense and can avoid calling setState() in an infinite loop within certain lifecycle methods like componentDidUpdate .

How does React renderer work exactly when we call setState?

The reconciliation process is the way React updates the DOM, by making changes to the component based on the change in state. When the request to setState() is triggered, React creates a new tree containing the reactive elements in the component (along with the updated state).

Does setState call componentDidMount?

You may call setState() immediately in componentDidMount() . It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won't see the intermediate state.


  1. prevState is provided by React along with props, both of which are optional.

    • Update 04/13/19: React has changed the setState function documentation by renaming prevState to updater. The callback function still takes two arguments; the state and props at the time the change is being applied.
  2. The parenthesis allow multiple lines where if you didn't use the parenthesis you'd be forced to used a return. You could use a single line but you don't need the curly braces.

    • Update: I forgot to mention a specific case where it is required to have parenthesis. If you're returning an object without a return statement you must wrap it in parenthesis. Thank you @joedotnot for catching that. So () => {foo: true} will throw an error because it looks like a function and foo: true is an invalid line. To fix this it must look like () => ({ foo: true })

Im use this. (Example)

const [modal, setModal] = useState(false);
const [dataAction, setDataAction] = useState({name: '', description: ''});

const _handleChangeName = (data) => {
    if(data.name)
        setDataAction( prevState  => ({ ...prevState,   name : data.name }));
    if(data.description)
        setDataAction( prevState  => ({ ...prevState,   description : data.description }));
  };