Vue triggers component re-render by it's reactivity mechanism, so developers can mutate states directly. Vue will detect the state change and trigger component rerender.
React triggers component re-render by manually setState and React will diff VDOM to check if it should re-render or not. Developers are recommended not to mutate state directly but create new one to replace original state so the original and new states can be shallowEqual efficiently.(immutable approach).
For example, there's a state as follows:
state = { a: 1, b: 2 }
// mutate state in Vue
state.a = 3// mutate state in Reactthis.setState({...state, a: 3 })
It seems that the reactivity mechanism is more intuitive and can write less code. I wonder what's the pros and cons between these two approaches? What scenario should I choose one over another?
There are a few key differences between the reactivity mechanism in Vue and the setState method in React:
Re-rendering behavior: In Vue, mutating a state directly will trigger a re-render of the component. In React, you have to call setState to trigger a re-render.
State immutability: In Vue, you can mutate state directly, but in React, you are encouraged to create a new state object to replace the original state. This is because React uses a technique called "shallow comparison" to determine whether a component should re-render or not. If you mutate the state directly, React will not be able to detect the change and the component will not re-render. By creating a new state object, React can perform a shallow comparison between the original and new state objects to determine whether the component should re-render.
Performance: Because React uses shallow comparison to determine whether a component should re-render, using immutable data structures can help improve performance. This is because shallow comparison is much faster on immutable data structures than on mutable ones.
Ultimately, the choice between these two approaches will depend on your specific needs and requirements. If you need to mutate state frequently and want to optimize for simplicity and ease of use, Vue's reactivity mechanism may be a good choice. If you want to optimize for performance and want to follow an immutable approach, React's setState method may be a better fit.