Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

init state without constructor in react

Tags:

import React, { Component } from 'react';  class Counter extends Component {   state = { value: 0 };    increment = () => {     this.setState(prevState => ({       value: prevState.value + 1     }));   };    decrement = () => {     this.setState(prevState => ({       value: prevState.value - 1     }));   };    render() {     return (       <div>         {this.state.value}         <button onClick={this.increment}>+</button>         <button onClick={this.decrement}>-</button>       </div>     )   } } 

Usually what I saw is people do this.state within the constructor function if he used es6 class. If he isn't he probably put the state using getinitialstate function. But above code (yes it's a working code), did not used either both. I have 2 question, what is state here? is that a local variable? if yes why it has no const? where does the prevState come from? why arrow function is used in setState? isn't it's easy to just do this.setState({value:'something'})?

like image 542
Jenny Mok Avatar asked Mar 24 '17 07:03

Jenny Mok


People also ask

Can we initialize state without constructor React?

You can also use state in React function components (without a constructor), but using higher-order components or render prop components.

How do you initialize a state in React?

Initializing state In class components, there are two ways to initialize state — in a constructor function or as a Class property. Constructor functions, introduced in ES6, is the first function called in a class when it is first instantiated — meaning when a new object is created from the class.

Is constructor necessary in React?

If you don't initialize state and you don't bind methods, you don't need to implement a constructor for your React component. The constructor for a React component is called before it is mounted. When implementing the constructor for a React. Component subclass, you should call super(props) before any other statement.

Is constructor mandatory in class component?

No, you don't need to.


2 Answers

I have 2 question, what is state here?

An instance property, like setting this.state = {value: 0}; in a constructor. It's using the Public Class Fields proposal currently at Stage 2. (So are increment and decrement, which are instance fields whose values are arrow functions so they close over this.)

is that a local variable?

No.

where does the prevState come from? why arrow function is used in setState? isn't it's easy to just do this.setState({value:'something'})?

From the documentation:

React may batch multiple setState() calls into a single update for performance.

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

For example, this code may fail to update the counter:

// Wrong this.setState({   counter: this.state.counter + this.props.increment, }); 

To fix it, use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:

// Correct this.setState((prevState, props) => ({   counter: prevState.counter + props.increment })); 

...which is exactly what the quoted code is doing. This would be wrong:

// Wrong increment = () => {   this.setState({     value: this.state.value + 1   }); }; 

...because it's relying on the state of this.state, which the above tells us not to; so the quoted code does this instead:

increment = () => {   this.setState(prevState => ({     value: prevState.value + 1   })); }; 

Here's proof that React may batch calls in a non-obvious way and why we need to use the callback version of setState: Here, we have increment and decrement being called twice per click rather than once (once by the button, once by a span containing the button). Clicking + once should increase the counter to 2, because increment is called twice. But because we haven't used the function callback version of setState, it doesn't: One of those calls to increment becomes a no-op because we're using a stale this.state.value value:

class Counter extends React.Component {   state = { value: 0 };    increment = () => {     /*     this.setState(prevState => ({       value: prevState.value + 1     }));     */     console.log("increment called, this.state.value = " + this.state.value);     this.setState({       value: this.state.value + 1     });   };      fooup = () => {     this.increment();   };    decrement = () => {     /*     this.setState(prevState => ({       value: prevState.value - 1     }));     */     console.log("decrement called, this.state.value = " + this.state.value);     this.setState({       value: this.state.value - 1     });   };      foodown = () => {     this.decrement();   };    render() {     return (       <div>         {this.state.value}         <span onClick={this.fooup}>           <button onClick={this.increment}>+</button>         </span>         <span onClick={this.foodown}>           <button onClick={this.decrement}>-</button>         </span>       </div>     )   } }  ReactDOM.render(   <Counter />,   document.getElementById("react") );
<div id="react"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

With the function callback, it works correctly (no calls to increment become no-ops):

class Counter extends React.Component {   state = { value: 0 };    increment = () => {     this.setState(prevState => {       console.log("Incrementing, prevState.value = " + prevState.value);       return {         value: prevState.value + 1       };     });   };      fooup = () => {     this.increment();   };    decrement = () => {     this.setState(prevState => {       console.log("Decrementing, prevState.value = " + prevState.value);       return {         value: prevState.value - 1       };     });   };      foodown = () => {     this.decrement();   };    render() {     return (       <div>         {this.state.value}         <span onClick={this.fooup}>           <button onClick={this.increment}>+</button>         </span>         <span onClick={this.foodown}>           <button onClick={this.decrement}>-</button>         </span>       </div>     )   } }  ReactDOM.render(   <Counter />,   document.getElementById("react") );
<div id="react"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

In this case, of course, we can look at the render method and say "Hey, increment will get called twice during a click, I'd better use the callback version of setState." But rather than assuming it's safe to use this.state when determining next state, best practice is not to assume that. In a complex component, it's easy to use mutator methods in a way that the author of the mutator method may not have thought of. Hence the statement by the React authors:

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

like image 63
T.J. Crowder Avatar answered Oct 31 '22 20:10

T.J. Crowder


About the question 2, refer to Dan's great answer here: Do I need to use setState(function) overload in this case?


  1. No it's not a local variable. It's the same as declaring this.state in constructor.

  2. Yes in that case you can just use this.setState({ value: this.state.value + 1 }), the result will be the same.

But note that by using functional setState you can have some benefits:

  1. the setState function can be reused if you declare it outside:

    const increment = prevState => ({   value: prevState.value + 1 }) 

    now if you have several components need to use this function, you can just import and reuse the logic everywhere.

    this.setState(increment) 
  2. React squashes several setState and executes them in batch. This may cause some unexpected behaviors. Please see the following example:

    http://codepen.io/CodinCat/pen/pebLaZ

    add3 () {   this.setState({ count: this.state.count + 1 })   this.setState({ count: this.state.count + 1 })   this.setState({ count: this.state.count + 1 }) } 

    executing this function the count will only plus 1

    If you use functional setState:

    http://codepen.io/CodinCat/pen/dvXmwX

    const add = state => ({ count: state.count + 1 }) this.setState(add) this.setState(add) this.setState(add) 

    count will +3 as you expected.

You can see the docs here: https://facebook.github.io/react/docs/react-component.html#setstate

like image 22
CodinCat Avatar answered Oct 31 '22 19:10

CodinCat