DEV Community

Gunabalan.S
Gunabalan.S

Posted on • Edited on

1

Use callback in setState when referencing the previous state.eslintreact/no-access-state-in-setstate

Example

       const actions = this.state.actions.filter((item) => item.key !== key2);
       this.setState({ actions, more_action: 'add' });

Enter fullscreen mode Exit fullscreen mode

Solution

      this.setState((prevState) => {
        const newActions = prevState.actions.filter((item) => item.key !== key2);
        return { actions: newActions, more_action: 'add' };
      });
Enter fullscreen mode Exit fullscreen mode

Note
prevState is available in setState callback, which is important for avoiding race conditions and ensuring that state updates are based on the latest values.

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay