简体   繁体   中英

How to use useMemo replacing useEffect?

I have options array for month and I am using it in useEffect but getting warning for deps. Kindly guide how to use useMemo . I am getting warning as given below: The 'options' array makes the dependencies of useEffect Hook (at line 83) change on every render. To fix this, wrap the initialization of 'options' in its own useMemo Hook react-hooks/exhaustive-deps

const options = [];

useEffect(() => {
  if (financialMonth) {
    options.forEach((item) => {
      if (Number(item.value) === Number(financialMonth)) {
        setMonthDefault(item.text);
      }
    });
    if (financialMonth.length === 0) setMonthDefault("April");
  }
}, [financialMonth, options]);

Simply:

const options = useMemo(() => [], [])

If you have a constant array of values (if it does not depend on state or props), then consider putting it outside of the component. That way you won't have to worry about useMemo or having it in the useEffect dependency array.

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