How can I force component to re-render with hooks in React?

前端 未结 16 2217
误落风尘
误落风尘 2020-11-29 00:28

Considering below hooks example

   import { useState } from \'react\';

   function Example() {
       const [count, setCount] = useState(0);

       return         


        
16条回答
  •  -上瘾入骨i
    2020-11-29 01:19

    As the others have mentioned, useState works - here is how mobx-react-lite implements updates - you could do something similar.

    Define a new hook, useForceUpdate -

    import { useState, useCallback } from 'react'
    
    export function useForceUpdate() {
      const [, setTick] = useState(0);
      const update = useCallback(() => {
        setTick(tick => tick + 1);
      }, [])
      return update;
    }
    

    and use it in a component -

    const forceUpdate = useForceUpdate();
    if (...) {
      forceUpdate(); // force re-render
    }
    

    See https://github.com/mobxjs/mobx-react-lite/blob/master/src/utils.ts and https://github.com/mobxjs/mobx-react-lite/blob/master/src/useObserver.ts

提交回复
热议问题