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

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

Considering below hooks example

   import { useState } from \'react\';

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

       return         


        
相关标签:
16条回答
  • 2020-11-29 01:00

    You can (ab)use normal hooks to force a rerender by taking advantage of the fact that React doesn't print booleans in JSX code

    // create a hook
    const [forceRerender, setForceRerender] = React.useState(true);
    
    // ...put this line where you want to force a rerender
    setForceRerender(!forceRerender);
    
    // ...make sure that {forceRerender} is "visible" in your js code
    // ({forceRerender} will not actually be visible since booleans are
    // not printed, but updating its value will nonetheless force a
    // rerender)
    return (
      <div>{forceRerender}</div>
    )
    
    
    0 讨论(0)
  • 2020-11-29 01:02

    React Hooks FAQ official solution for forceUpdate:

    const [_, forceUpdate] = useReducer((x) => x + 1, 0);
    // usage
    <button onClick={forceUpdate}>Force update</button>
    

    Working example

    const App = () => {
      const [_, forceUpdate] = useReducer((x) => x + 1, 0);
    
      return (
        <div>
          <button onClick={forceUpdate}>Force update</button>
          <p>Forced update {_} times</p>
        </div>
      );
    };
    
    ReactDOM.render(<App />, document.getElementById("root"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.1/umd/react.production.min.js" integrity="sha256-vMEjoeSlzpWvres5mDlxmSKxx6jAmDNY4zCt712YCI0=" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.1/umd/react-dom.production.min.js" integrity="sha256-QQt6MpTdAD0DiPLhqhzVyPs1flIdstR4/R7x4GqCvZ4=" crossorigin="anonymous"></script>
    <script>var useReducer = React.useReducer</script>
    <div id="root"></div>

    0 讨论(0)
  • 2020-11-29 01:05

    Simple code

    const forceUpdate = React.useReducer(bool => !bool)[1];
    

    Use:

    forceUpdate();
    
    0 讨论(0)
  • 2020-11-29 01:06

    Potential option is to force update only on specific component using key. Updating the key trigger a rendering of the component (which failed to update before)

    For example:

    const [tableKey, setTableKey] = useState(1);
    ...
    
    useEffect(() => {
        ...
        setTableKey(tableKey + 1);
    }, [tableData]);
    
    ...
    <DataTable
        key={tableKey}
        data={tableData}/>
    
    0 讨论(0)
  • 2020-11-29 01:07

    My variation of forceUpdate is not via a counter but rather via an object:

    // Emulates `forceUpdate()`
    const [unusedState, setUnusedState] = useState()
    const forceUpdate = useCallback(() => setUnusedState({}), [])
    

    Because {} !== {} every time.

    0 讨论(0)
  • 2020-11-29 01:08

    This will render depending components 3 times (arrays with equal elements aren't equal):

    const [msg, setMsg] = useState([""])
    
    setMsg(["test"])
    setMsg(["test"])
    setMsg(["test"])
    
    0 讨论(0)
提交回复
热议问题