I am use Suspense to lazy load my page components in my app.
const Page = lazy(() => import('./Page'));
<Suspense>
<MyAuthRoute
path='/page/:id'
component={Page}
/>
</Suspense>
I am also using Context for state management thorough-out the app. Inside of my MyContext
, I have:
const [pageId, setPageId] = useState();
<MyContext.Provider value={{pageId, setPageId}}>
{children}
</MyContext.Provider>
In my page component, I want to set pageId
in MyContext to the id that was passed in the URL, but I am receiving an error: Cannot update a component (MyContextProvider) while rendering a different component
const { id } = useParams();
const { pageId, setPageId } = useContext(MyContext)
setPageId(id);
Does setPageId
need to be in a useEffect? If so, why?
CodePudding user response:
Yes, you'll need to wrap the set call in a useEffect
, React added the warning you are seeing in version 16. As a rule of thumb it is recommended to avoid side effects while rendering, there is a GitHub issue where why this warning was added is discussed at great length, where Dan Abramov explains it as:
... The answer to “why” isn’t any more complex than “if one component triggers updates on other components during rendering, it becomes very hard to trace the data flow of your app because it no longer goes from top down”. So if you do that you’re kind of throwing away the benefits of React. ...
Source: Dan's comment on the React Issue