Skip to content

Cannot update a component while rendering a different component #77

@yoavst

Description

@yoavst

Given the following code:

function App() {
    const [count, setCount] = useLocalStorageState<number>('count', { defaultValue: 0 })

    if (count > 5) {
        setCount(0)
    }
    return <div className="card">
                <button
                    onClick={() => {
                        setCount((count) => count + 1)
                    }}
                >
                    count is {count}
                </button>
            </div>
}

The setCount(0) line will throw a warning of:

App.tsx:11 Warning: Cannot update a component (`App`) while rendering a different component (`App`). To locate the bad setState() call inside `App`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
    at App (http://localhost:5173/src/App.tsx?t=1733173762885:24:29)
    printWarning @ chunk-XPR23Y44.js?v=1a9b5ea3:519
    error @ chunk-XPR23Y44.js?v=1a9b5ea3:503
    warnAboutRenderPhaseUpdatesInDEV @ chunk-XPR23Y44.js?v=1a9b5ea3:19791
    scheduleUpdateOnFiber @ chunk-XPR23Y44.js?v=1a9b5ea3:18544
    forceStoreRerender @ chunk-XPR23Y44.js?v=1a9b5ea3:11997
    handleStoreChange @ chunk-XPR23Y44.js?v=1a9b5ea3:11979
    onChange @ use-local-storage-state.js?v=f253ee13:25
    triggerCallbacks @ use-local-storage-state.js?v=f253ee13:99
    (anonymous) @ use-local-storage-state.js?v=f253ee13:68
    App @ App.tsx:11
    renderWithHooks @ chunk-XPR23Y44.js?v=1a9b5ea3:11546
    updateFunctionComponent @ chunk-XPR23Y44.js?v=1a9b5ea3:14580
    beginWork @ chunk-XPR23Y44.js?v=1a9b5ea3:15922
    beginWork$1 @ chunk-XPR23Y44.js?v=1a9b5ea3:19751
    performUnitOfWork @ chunk-XPR23Y44.js?v=1a9b5ea3:19196
    workLoopSync @ chunk-XPR23Y44.js?v=1a9b5ea3:19135
    renderRootSync @ chunk-XPR23Y44.js?v=1a9b5ea3:19114
    performSyncWorkOnRoot @ chunk-XPR23Y44.js?v=1a9b5ea3:18872
    flushSyncCallbacks @ chunk-XPR23Y44.js?v=1a9b5ea3:9117
    (anonymous) @ chunk-XPR23Y44.js?v=1a9b5ea3:18625

This pattern is recommended by react docs.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions