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

前端 未结 16 2216
误落风尘
误落风尘 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:17

    For regular React Class based components, refer to React Docs for the forceUpdate api at this URL. The docs mention that:

    Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render()

    However, it is also mentioned in the docs that:

    If your render() method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate().

    So, although use cases for using forceUpdate might be rare, and I have not used it ever, however I have seen it used by other developers in some legacy corporate projects that I have worked on.

    So, for the equivalent functionality for Functional Components, refer to the React Docs for HOOKS at this URL. Per the above URL, one can use the "useReducer" hook to provide a forceUpdate functionality for Functional Components.

    A working code sample that does not use state or props is provided below, which is also available on CodeSandbox at this URL

    import React, { useReducer, useRef } from "react";
    import ReactDOM from "react-dom";
    
    import "./styles.css";
    
    function App() {
      // Use the useRef hook to store a mutable value inside a functional component for the counter
      let countref = useRef(0);
    
      const [, forceUpdate] = useReducer(x => x + 1, 0);
    
      function handleClick() {
        countref.current++;
        console.log("Count = ", countref.current);
        forceUpdate(); // If you comment this out, the date and count in the screen will not be updated
      }
    
      return (
        

    {new Date().toLocaleString()}

    You clicked {countref.current} times

    ); } const rootElement = document.getElementById("root"); ReactDOM.render(, rootElement);

    NOTE: An alternate approach using the useState hook (instead of useReducer) is also available at this URL.

提交回复
热议问题