Difference between declarative and imperative in React.js?

后端 未结 9 543
日久生厌
日久生厌 2020-11-30 17:29

Recently I\'ve been studying a lot about the functionality and the ways to use the Facebook JavaScript library React.js. When speaking of its differences to the rest of the

9条回答
  •  醉话见心
    2020-11-30 17:46

    It is best to compare React (declarative) and JQuery (imperative) to show you the differences.

    In React, you only need to describe the final state of your UI in the render() method, without worrying about how to transition from previous UI state to the new UI state. E.g.,

    render() {
      const { price, volume } = this.state;
      const totalPrice = price * volume;
    
      return (
        
    ) }

    On the other hand, JQuery requires you to transition your UI state imperatively, e.g, selecting the label elements and update their text and CSS:

    updatePrice(price) {
      $("#price-label").val(price);
      $("#price-label").toggleClass('expansive', price > 100);
      $("#price-label").toggleClass('cheap', price < 100);
    
      // also remember to update UI depending on price 
      updateTotalPrice();
      ... 
    }
    
    updateVolume(volume) {
      $("#volume-label").val(volume);
      $("#volume-label").toggleClass('high', volume > 1000);
      $("#volume-label").toggleClass('low', volume < 1000);
      
      // also remember to update UI depending on volume
      updateTotalPrice();
      ... 
    }
    
    updateTotalPrice() {
      const totalPrice = price * volume;
      $("#total-price-label").val(totalPrice);
      ...
    }
    

    In the real world scenario, there will be many more UI elements to be updated, plus their attributes (e.g., CSS styles, and event listeners), etc. If you do this imperatively using JQuery, it will become complex and tedious; it is easy to forget to update some parts of the UI, or forget to remove old event handlers (cause memory leak or handler fires multiple times), etc. This is where bugs happen, i.e., UI state and the model state are out of sync.

    States out of sync will never happen to React's declarative approach, because we only need to update the model state, and React is responsible to keep the UI and model states in sync.

    • Under the hook, React will updates all changed DOM elements using imperative code.

    You may also read my answer for What is the difference between declarative and imperative programming?.

    PS: from above jQuery example, you may think what if we put all the DOM manipulations in a updateAll() method, and call it every time when any of our model state changes, and the UI will never be out of sync. You are correct, and this is effectively what React does, the only difference is that jQuery updateAll() will cause many unnecessary DOM manipulations, but React will only update changed DOM elements using its Virtual DOM Diffing Algorithm.

提交回复
热议问题