score:1

your effect is triggered based on the "shopusers" prop, which itself triggers a redux action that updates the "shopusers" prop and thats why it keeps infinitely firing.

i think what you want to optimize is the rendering of your component itself, since you're already using redux, i'm assuming your props/state are immutable, so you can use react.memo to re-render your component only when one of its props change.

also you should define your state/props variable outside of your hooks since they're used in the scope of the entire function like so.

in your case, if you pass an empty array as a second param to memo, then it will only fire on componentdidmount, if you pass null/undefined or dont pass anything, it will be fired on componentdidmount + componentdidupdate, if you want to optimise it that even when props change/component updates the hook doesn't fire unless a specific variable changes then you can add some variable as your second argument

react.memo(function(props){
  const [isloading, setloading] = usestate(false);
  const { getstoreusers, shopusers } = props;
  useeffect(() => {
    setloading(true);
    getstoreusers().then(() => {
      setloading(false);
    }).catch((err) => {
      setloading(false);
    });
  }, []);
...
})

score:7

you can make a custom hook to do what you want:

in this example, we replace the last element in the array, and see the output in the console.

import react, { usestate, useeffect, useref } from "react";
import reactdom from "react-dom";
import { isequal } from "lodash";

const useprevious = value => {
  const ref = useref();
  useeffect(() => {
    ref.current = value;
  });
  return ref.current;
};

const app = () => {
  const [arr, setarr] = usestate([2, 4, 5]);
  const prevarr = useprevious(arr);

  useeffect(() => {
    if (!isequal(arr, prevarr)) {
      console.log(`array changed from ${prevarr} to ${arr}`);
    } 
  }, [prevarr]);

  const change = () => {
    const temp = [...arr];
    temp.pop();
    temp.push(6);
    setarr(temp);
  };

  return (
      <button onclick={change}>change last array element</button>
  )
};

const rootelement = document.getelementbyid("root");
reactdom.render(<app />, rootelement);

live example here.


Related Query

More Query from same tag