Interaction between redux and useEffect

Viewed 73

I was working on a function which loads some data to a component artificially ie. recreates a page display based on the uploaded data. I am facing issues with when useEffect gets called. Here is the code:

const funcA = (props) => {
    let a = [1, 2, 3];
    let b = [2, 3];
    setSelected(a);
    setParam(b);
    return (
        <div>...</div>
);
}

const funcB = (props) => {
    useEffect(
        () => {
            setParam([]);
        },
        [props.selected]
    );
    return (<div>...</div>);
}

setSelected() and setParam() are actions which modify my redux store. Now When I change selected using setSelected() in funcA, useEffect is called in funcB which modifies the param data based on selected values. I thought this should not be an issue as I am calling setParam() after calling setSelected but it seems useEffect is getting executed after setParam().

So long story short, this is the order I want them to execute in:

  1. setSelected()
  2. useEffect() (because of change in selected)
  3. setParam()

but they are executing in this order:

  1. setSelected()
  2. setParam()
  3. useEffect() (because of change in selected)

Any help is appreciated. Thanks!!

1 Answers

In the react world you should generally not rely on the order in which your setSomething() functions are called.

React "collects" state update calls, and decides the most efficient way to update the state.

Instead of thinking in "call order", you should think in "what should state B be if state A is X ?".
Instead of "change state if user clicks", think of "what does the user want so get/see ?".

Not good:

  1. setSelected()
  2. useEffect() (because of change in selected)
  3. setParam()

Better:

  1. setSelected()
  2. useEffect() (calls setParam(), because of change in selected)
  3. useEffect() (calls setParam(), because of ... why ?)

You probably have to rethink, and change the structure of your state a bit.

Related