Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: Cannot update a component (xxx) while rendering a different component (yyy) on user click #22633

Closed
alicerocheman opened this issue Oct 27, 2021 · 6 comments
Labels
Resolution: Stale Automatically closed due to inactivity Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug

Comments

@alicerocheman
Copy link

I'm encountering the Cannot update a component (xxx) while rendering a different component (yyy) on user click.
The state setter is called inside a useCallback, which is called several components "below", inside a useCallback.
As the user decides when they click, I don't understand how I could prevent this error, and am not sure whether the error should fire in this case.

React version: 17.0.2

Steps To Reproduce

  1. create a Parent component that contains this:
  const [showError, setShowError] = useState(false);
  const [scrollToError, setScrollToError] = useState(false);
  const handleShowError = useCallback(() => {
    setShowError(true);
    setScrollToError(true);
  }, []);
  const handleStopShowingError = useCallback(() => {
    setShowError(false); // this produces the error when called in step 3
    setScrollToError(false);
  }, []);
  const handleStopScrollToError = useCallback(() => {
    setScrollToError(false);
  }, []);
  1. pass those through a child, and its child and its child FinalChild, that all do other things, including listening to contexts and updating stuff.
  2. in FinalChild, use the callbacks this way:
  const onClick = useCallback(() => {
    setIsOpen((isOpen) => {
      if (isOpen) {
        if (isValid) {
          handlers.handleComplete();
          return false;
        } else {
          handleShowError(); 
          return true;
        }
      } else {
        if (isDisabled) {
          handleShowError();
          return false;
        } else {
          handleStopShowingError(); // this produces the error (that goes up to parent in step 1)
          if (!isPreviousTabCompleted) handleCompletePreviousTabs(_index);
          return true;
        }
      }
    });
  }, [
    handleShowError,
    handleStopShowingError,
    handleCompletePreviousTabs,
    handlers,
    _index,
    isValid,
    isDisabled,
    isPreviousTabCompleted,
  ]);
  return <button onClick={onClick}>Click me</button>

Link to code example:
I couldn't reproduce outside of my working repo, as the error does not appear when render is fast on typical simple components.

The current behavior

When user clicks, I get the Cannot update a component (xxx) while rendering a different component (yyy) error

The expected behavior

Honnestly I don't know what should happen, it seems weird that the error pops up, even though I'm never calling the setter outside of a hook (always inside a useCallback) and user should be able to click when they want... I understand the error is there to inform me that there is an issue with my code, but I don't know how I could improve this code. Shouldn't the useCallback deal with this?

@alicerocheman alicerocheman added the Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug label Oct 27, 2021
@alicerocheman alicerocheman changed the title Bug: Bug: Cannot update a component (xxx) while rendering a different component (yyy) on user click Oct 27, 2021
@lubieowoce
Copy link
Contributor

lubieowoce commented Nov 13, 2021

I couldn't find a reference for this, but it's possible that you're not allowed to do side-effects in the updater-function you pass to a setState.
(i'm assuming setIsOpen comes from a const [isOpen, setIsOpen] = useState(...)).

I.e. I don't think something like this is allowed:

const [first, setFirst] = useState(0);
const [second, setSecond] = useState(0);
const probablyIllegal = () => {
  setSecond((prevSecond) => {
    setFirst(0); // ❌❌❌
    return prevSecond + 1;
  }):
}

(This code by itself seems to work, but I imagine it'd break when you split it across multiple components, like yours is)

EDIT: Seems similar to #15240 (comment):

You cannot perform side effects in that callback, it must be a pure function that returns new state.

@gaearon
Copy link
Collaborator

gaearon commented Nov 13, 2021

This sounds likely because updater functions run during rendering.

@hubertlepicki
Copy link

To the good people that find this thread and are wondering what @gaearon tip means: you likely to have the following code in your child component:

if (someVariableChanged) {
  setSomeState(...)
}

In my case, I had to change it to useEffect like this:

useEffect(() => {
  setSomeState(...)
}, [someVariableChanged]

@jatinbansal1305
Copy link

The error you are encountering, "Cannot update a component while rendering a different component," typically occurs when you attempt to update the state of a component while it is still rendering. This can happen when you call a state setter function (like setShowError) inside a useCallback hook that is triggered during rendering.

To prevent this error, you can use the useEffect hook to perform state updates after the rendering is complete.

Copy link

This issue has been automatically marked as stale. If this issue is still affecting you, please leave any comment (for example, "bump"), and we'll keep it open. We are sorry that we haven't been able to prioritize it yet. If you have any new additional information, please include it with your comment!

@github-actions github-actions bot added the Resolution: Stale Automatically closed due to inactivity label Apr 10, 2024
Copy link

Closing this issue after a prolonged period of inactivity. If this issue is still present in the latest release, please create a new issue with up-to-date information. Thank you!

@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale Apr 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Resolution: Stale Automatically closed due to inactivity Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug
Projects
None yet
Development

No branches or pull requests

5 participants