Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React trigger useEffect when two things changes

Tags:

reactjs

I am trying to use react hooks and I want to run a function when two things change:

const Filter = ({ orderList, orders }) => {
  const [from, setFrom] = useState();
  const [to, setTo] = useState();
  const [filteredList, setFilteredList] = useState(orders);

  useEffect(() => {
    const filteredOrders = orders.filter(function(item) {
      return item.order_number >= from && item.order_number <= to;
    });
    setFilteredList(filteredOrders);
    console.log(filteredList);
  }, [from, to]);

more precisely I would like to filter the array only when BOTH from and to states changes, this is because I am trying to filter an array from some inputs defined by the user.

How can I achieve this?

like image 548
sanna Avatar asked Jul 22 '26 07:07

sanna


1 Answers

You would not be able to accomplish this by passing in more arguments into useEffect(), by default that will cause useEffect() to execute as long as one item is changed.

You could however combine useEffect with useRef to accomplish this. We will use useRef to store the previous values of the states and compare that to our new state values.

See codesandbox for example: https://codesandbox.io/s/heuristic-nobel-6ece5

const App = () => {
  const [from, setFrom] = useState();
  const [to, setTo] = useState();

  const previousValues = useRef({ from, to });

  useEffect(() => {
    if (
      previousValues.current.from !== from &&
      previousValues.current.to !== to
    ) {
      //your logic here
      console.log("both changed")
      previousValues.current = { from, to };
    }
  });

  return (
    <div>
      <input
        placeholder="from"
        value={from}
        onChange={e => setFrom(e.target.value)}
      />
      <input
        placeholder="to"
        value={to}
        onChange={e => setTo(e.target.value)}
      />
    </div>
  );
};
like image 129
Chris Ngo Avatar answered Jul 25 '26 00:07

Chris Ngo