Why can't I directly modify a component's state, really?

前端 未结 7 826
感动是毒
感动是毒 2020-11-21 22:40

I understand that React tutorials and documentation warn in no uncertain terms that state should not be directly mutated and that everything should go through setState

相关标签:
7条回答
  • 2020-11-21 23:11

    It surprises me that non of the current answers talk about pure/memo components. These components only re-render when a change in one of the props is detected.

    Say you mutate state directly and pass, not the value, but the over coupling object to the component below. This object still has the same reference as the previous object, meaning that pure/memo components wont re-render, even though you mutated one of the properties.

    Since you don't always know what type of component you are working with when importing them from libraries, this is yet another reason to stick the non-mutating rule.

    Here is an example of this behaviour in action (using R.evolve to simplify creating a copy and updating nested content):

    class App extends React.Component {
      state = {some: {rather: {deeply: {nested: {stuff: 1}}}}};
      
      mutatingIncrement = () => {
        this.state.some.rather.deeply.nested.stuff++;
        this.setState({});
      }
      nonMutatingIncrement = () => {
        this.setState(R.evolve(
          {some: {rather: {deeply: {nested: {stuff: n => n + 1}}}}}
        ));
      }
    
      render() {
        return <div>
          Pure Component: <PureCounterDisplay {...this.state} />
          <br />
          Normal Component: <CounterDisplay {...this.state} />
          <br />
          <button onClick={this.mutatingIncrement}>mutating increment</button>
          <button onClick={this.nonMutatingIncrement}>non-mutating increment</button>
        </div>;
      }
    }
    
    const CounterDisplay = (props) => (
      <React.Fragment>
        Counter value: {props.some.rather.deeply.nested.stuff}
      </React.Fragment>
    );
    const PureCounterDisplay = React.memo(CounterDisplay);
    
    ReactDOM.render(<App />, document.querySelector("#root"));
    <script src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/ramda@0/dist/ramda.min.js"></script>
    <div id="root"></div>

    0 讨论(0)
  • 2020-11-21 23:15

    the simplest answer to "

    Why can't I directly modify a component's state:

    is all about Updating phase.

    when we update the state of a component all it's children are going to be rendered as well. or our entire component tree rendered.

    but when i say our entire component tree is rendered that doesn’t mean that the entire DOM is updated. when a component is rendered we basically get a react element, so that is updating our virtual dom.

    React will then look at the virtual DOM, it also has a copy of the old virtual DOM, that is why we shouldn’t update the state directly, so we can have two different object references in memory, we have the old virtual DOM as well as the new virtual DOM.

    then react will figure out what is changed and based on that it will update the real DOM accordingly .

    hope it helps.

    0 讨论(0)
  • 2020-11-21 23:15

    My current understanding is based on this and this answer:

    IF you don't use shouldComponentUpdate or any other lifecycle methods (like componentWillReceiveProps, componentWillUpdate, and componentDidUpdate) where you compare the old and new props/state

    THEN

    its fine to mutate state and then call setState(), otherwise it is not fine.

    0 讨论(0)
  • 2020-11-21 23:21

    To avoid every time to create a copy of this.state.element you can use update with $set or $push or many others from immutability-helper

    e.g.:

    import update from 'immutability-helper';
    
    const newData = update(myData, {
      x: {y: {z: {$set: 7}}},
      a: {b: {$push: [9]}}
    });
    
    0 讨论(0)
  • 2020-11-21 23:21

    setState trigger re rendering of the components.when we want to update state again and again we must need to setState otherwise it doesn't work correctly.

    0 讨论(0)
  • 2020-11-21 23:23

    This answer is to provide enough information to not change/mutate the state directly in React.

    React follows Unidirectional Data Flow. Meaning, the data flow inside react should and will be expected to be in a circular path.

    React's Data flow without flux

    To make React work like this, developers made the React similar to functional programming. The thumb rule of functional programming is immutability. Let me explain it loud and clear.

    How does the unidirectional flow works?

    • states are a data store which contains the data of a component.
    • The view of a component renders based on the state.
    • When the view needs to change something on the screen, that value should be supplied from the store.
    • To make this happen, React provides setState() function which takes in an object of new states and does an compare and merge(similar to object.assign()) over the previous state and adds the new state to the state data store.
    • Whenever the data in the state store changes, react will trigger an re-render with the new state which the view consumes and shows it on the screen.

    This cycle will continue throughout the component's lifetime.

    If you see the above steps, it clearly shows a lot of things are happening behind when you change the state. So, when you mutate the state directly and call setState() with an empty object. The previous state will be polluted with your mutation. Due to which, the shallow compare and merge of two states will be disturbed or won't happen, because you'll have only one state now. This will disrupt all the React's Lifecycle Methods.

    As a result, your app will behave abnormal or even crash. Most of the times, it won't affect your app because all the apps which we use for testing this are pretty small.

    And another downside of mutation of Objects and Arrays in JavaScript is, when you assign an object or an array, you're just making a reference of that object or that array. When you mutate them, all the reference to that object or that array will be affected. React handles this in a intelligent way in the background and simply give us an API to make it work.

    Most common errors done when handling states in React

    // original state
    this.state = {
      a: [1,2,3,4,5]
    }
    
    // changing the state in react
    // need to add '6' in the array
    
    // bad approach
    const b = this.state.a.push(6)
    this.setState({
      a: b
    }) 
    

    In the above example, this.state.a.push(6) will mutate the state directly. Assigning it to another variable and calling setState is same as what's shown below. As we mutated the state anyway, there's no point assigning it to another variable and calling setState with that variable.

    // same as 
    this.state.a.push(6)
    this.setState({})
    

    Most of the people does this. This is so wrong. This breaks the beauty of React and it'll make you a bad programmer.

    So, What's the best way to handle states in React? Let me explain.

    When you need to change 'something' in the existing state, first get a copy of that 'something' from the current state.

    // original state
    this.state = {
      a: [1,2,3,4,5]
    }
    
    // changing the state in react
    // need to add '6' in the array
    
    // create a copy of this.state.a
    // you can use ES6's destructuring or loadash's _.clone()
    const currentStateCopy = [...this.state.a]
    

    Now, mutating currentStateCopy won't mutate the original state. Do operations over currentStateCopy and set it as the new state using setState().

    currentStateCopy.push(6)
    this.state({
      a: currentStateCopy
    })
    

    This is beautiful, right?

    By doing this, all the references of this.state.a won't get affected until we use setState. This gives you control over your code and this'll help you write elegant test and make you confident about the performance of the code in production.

    To answer your question,

    Why can't I directly modify a component's state?


    Yes, you can. But, you need to face the following consequences.

    1. When you scale, you'll be writing unmanageable code.
    2. You'll lose control of state across components.
    3. Instead of using React, you'll be writing custom codes over React.

    Immutability is not necessary thing because JavaScript is single threaded. But, It's a good to follow practice which will help you in the long run.

    PS. I've written about 10000 lines of mutable React JS code. If it breaks now, I don't know where to look into because all the values are mutated somewhere. When I realized this, I started writing immutable code. Trust me! That's the best thing you can do it to a product or an app.

    Hope this helps!

    0 讨论(0)
提交回复
热议问题