简体   繁体   中英

Re-initialized state

I have a complex component with some "dynamic" imports.

I recreate my component tree on codesandbox: https://codesandbox.io/s/clever-rosalind-t3cfm?file=/src/App.js:298-302

I have an App.js file where I have a list of objects. Each object, render a RenderWidget component.

Inside RenderWidget , I need to get a "dynamic" comp. (I recreated that with a simple function, but i have more complexity in that part). So I wrapped the comp on useMemo to avoid component re-creation. (useMemo has a console.log to check if the Comp is re-initializated)

Inside the Comp , we have a useState declaration with the following initial value:

const getData = () => {
   console.log("getData called");
   return Math.random();
 };

const [data, setData] = useState(getData());

If You click on H1, we force an update on App.js. If you check the console, You get "getData called" each time that you click on H1.

Why?

If parent component props have changed it will re-render all of its children, you can use React.memo to prevent unnecessary re-render.

I also suggest you to read this article , it's written by the author of the react core team, in addition to memo, there are other ways to prevent re-rendering

export default memo(function RenderWidget() {
  const LocalComp = useMemo(() => {
    console.log("NO RE-INITIALIZED");
    return getComp();
  }, []);

  return <LocalComp />;
});

I got the answer!

For the "lazy" initial value, we need to call the function like this:

// Replace that
const [data, setData] = useState(getData());

// With that
const [data, setData] = useState(() => getData());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM