Paul
Paul

Reputation: 1441

Using two useeffect react hooks

I try to use react with hooks. I have this state:

const [state, setState] = useState<State>({
    titel: "",
    somethingElse: "",
    tabledata: [],
});

I have two useeffect:

// componentDidMount, Initial variable deklaration
useEffect(() => {
    //Do something

    //Set initial states
    setState({
        ...state,
        titel: props.titel,
        somethingElse: props.somethingElse,
    })

}, []);

// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {

    //Do something and generate tabledata
    let tabledata ....

    //Set tabledata
    setState({
        ...state,
        tabledata: tabledata,
    })

}, [props.taenzer]);

Now I have the behavior, that the second useeffect is overwriting the first useeffect setState command. My variable titel and somethingElse is always empty.

Now I could change my deklaration of state, something in this way:

const [titel, setTitel] = useState<>({
    titel = ""
});
const [somethingElse, setSomethingElse] = useState<>({
    somethingElse = ""
});

But this makes the whole unclear and it is not so easy to set the state of several variables in one time like we could with setState(...state, titel="Hello", somethingElse="Else")

Any other possibility?

Upvotes: 1

Views: 1928

Answers (1)

Joseph D.
Joseph D.

Reputation: 12174

the second useeffect is overwriting the first useeffect setState

useState function doesn't automatically merge the state. So you would need to make use of the previous state accessible via callback.

useEffect(
  () => {
    const tabledata = ...
    setState(prevState => ({ // use previous state
      ...prevState,
      tabledata
    }))
  }, [props.taenzer]
)

Any other possibility?

You can have lazy initialization of your state via props and remove the first effect (without dependency)

const [{ title, somethingElse, tabledata }, setState] = useState<State>({
    ...props,
    tabledata: [],
});

Upvotes: 4

Related Questions