preface

Since the official release of Vue3.0, the core responsive part of Vue3.0 has been separated into the @vue/ Reactivity package. That is to say, we can do other pleasant things with @vue/ Reactivity independently of the Vue framework 😊. Why not use @vue/reactivity in React and build a reactive view instead of calling this.setState and useState every time you update the view?

😂😂😂 to quantize production and reuse logic, I wrote a custom hook-UsereActive in the Function component and a higher-order reactiveHoc in the class component.

React vue?

The actual purpose of writing this article is:

  • 1 Let’s go over itvue3.0The responsive principle,reactiveeffect.
  • How to write a responsive customizationhooks, learn to write customhook.
  • 3 How to write a responsiveHOCAnd learn to writehoc.

Function component – custom hooks – useReactive

write

UseReactive Custom hooks

import { reactive, effect  } from '@vue/reactivity'
import React, {  useRef , useEffect, useMemo, useState } from 'react'
function useReactive (initState){
   const reactiveState = useRef(initState) // state 
   const [  ,forceUpdate ] = useState(0)
   const state = useMemo(() = > reactive(reactiveState.current)  ,[ reactiveState.current ]) 
   useEffect(() = >{
       let isdep = false
       effect(() = >{
           for(let i in state ){ state[i] } // Rely on collection
           isdep && forceUpdate(num= > num + 1)  // Force an update
           if(! isdep) isdep =true
       })
   },[ state ])
   return state
}
Copy the code

Ideas:

  • (1) withuseRefSave the reactive object and build the reactive. WhyuseRefIn the function component performing updates, onlyRef-HooksI’m always using the original object, the one before thathooksThat’s the principle. The advantage of doing this is to prevent the reactive object from being lost when the function component is updated.
  • (2) withuseMemoCache reactive objects whenRefObject is tampered with and reactive is rebuilt.
  • (3) withuseEffectDo reactive dependency collection with switchesisdepTo prevent initialization@vue/reactivitytheeffectCaused when initialization is executedforceUpdateRaised, additional component updates.
  • (4) with auseStateTo force updates.
  • (5) in theeffectObject,for(let i in state ){ state[i] }traverseRefObject to do dependency collection.

use

function Index(){
   const state = useReactive({ number:1  , name:'alien' })
   return <div className="box" >
       <div className="show" >
           <div>Your name is: {state.name}</div>
           <div>{new Array (state number). The fill (0). The map (() = > '👽')}</div>
       </div>
       <div className="constrol" >
            <div> <button onClick={() = >State. Number++} > 👽 + +</button> </div>
            <div> <button onClick={() = >State. The number -- --} > 👽 -</button>  </div>
            <input placeholder="Name" value={state.name}  onChange={ (e:any) = >  state.name = e.target.value   }  />       
       </div>
   </div>
}
Copy the code

The effect

Class component – Reverse inherited hoc-reactiveHoc

In the function component, we can use custom hooks to build responsiveness; So how do we build responsiveness in a class component? Every time we introduce Reactive and Effect into a business component and manually bind it, it’s obviously not practical or desirable, and that’s where hoc higher-order components come in. Let’s move on:

write

ReactiveHoc high-level components

import { reactive , effect  } from '@vue/reactivity'
import React from 'react'
function reactiveHoc(Component){
    const self_componentDidMount = Component.prototype.componentDidMount
    return class WrapComponent extends Component{
        constructor(props){
            super(props)
            this.state = reactive(this.state)
        }
        __isFirst = false
        componentDidMount(){
            effect(() = >{
                for(let i in this.state ){ this.state[i] }  // Build responsive
                this.__isFirst && this.forceUpdate()
                !this.__isFirst && (this.__isFirst = true )     
            }) 
            self_componentDidMount && self_componentDidMount.call(this)}}}Copy the code

Ideas:

  • 1.Why reverse inheritanceHOC?Because we can pass an inheritance anywayhocAccess to internalstateState, for internalstate,reactiveReactive processing.
  • (2) Hijack component cyclecomponentDidMountIn thehocthecomponentDidMountAlso do dependency collection in.

use

@reactiveHoc
class Index extends React.Component{
    constructor(props){
        super(props)
        this.state={
            number:0.name:'alien'}}componentDidMount(){
        console.log(6666)}render(){
        const { state } :any= this
        return <div className="box" >
        <div className="show" >
            <div>Your name is: {state.name}</div>
            <div>{new Array (state number). The fill (0). The map (() = > '👽')}</div>
        </div>
        <div className="constrol" >
             <div> <button onClick={() = >State. Number++} > 👽 + +</button> </div>
             <div> <button onClick={() = >State. The number -- --} > 👽 -</button>  </div>
             <input placeholder="Name" value={state.name}  onChange={ (e:any) = >  state.name = e.target.value   }  />       
        </div>
    </div>}}Copy the code

conclusion

The main purpose of this article is not to teach you how to build responsive responses in React using @vue/reactivity for fun. The main purpose of this article is to teach you how to write custom hooks and hoc in conjunction with the previous two articles. Advance the React technology stack early.

Finally, send rose, hand left lingering fragrance, feel a harvest of friends can give the author praise, pay attention to a wave, update the front end of the super core article.

If the article, do not understand the place, it is suggested to read the article:

The react – hooks trilogy

  • React-hooks how to use 150+ like 👍

  • React-hooks: React-hooks, custom hooks design patterns and their action 225+ 👍 Cool

  • React-hooks 730+ 👍 Thumbs up

react-hoc

  • React Advanced Components (HOC) 320 +Praise 👍

The principle of VUE3.0 responsiveness

  • The principle of VUE3.0 responsiveness 250 +Praise 👍