Updating an atom unmounts and mounts component inside the Styled component #2606
-
When you update an atom inside a page, components in the page that are placed inside a styled component gets unmounted an mounted again. (NextJs | Typescript | MUI) I created a test atom and inside page.tsx(app/page.tsx) I am updating the atom on an interval. Everytime atom is updated, component (StyledComponentContent) inside a styled component (here it is a styled AppBar mui component but any styled component has the same effect) get unmounted and mounted again on every update. Component inside a non styled component (NonStyledComponent.tsx & NonStyledComponentContent.tsx) does not show the same behaviour. I believe this is an unintended behaviour. Start the Preview Externally in the CodeSandbox and view the console to see the constant unmounted/mounted logs coming from the component(StyledComponentContent) inside the styled AppBar. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Thanks for reporting. Can anyone dig into it and investigate more? Thanks! |
Beta Was this translation helpful? Give feedback.
-
You create the styled component Just create the styled component outside: const StyledComponent = () => {
// WRONG
// const AppBarStyled = styled(AppBar)(({ theme }) => ({ }));
return (
<AppBarStyled>
<StyledComponentContent></StyledComponentContent>
</AppBarStyled>
);
};
// CORRECT
const AppBarStyled = styled(AppBar)(({ theme }) => ({ })); |
Beta Was this translation helpful? Give feedback.
You create the styled component
AppBarStyled
inside another React component but they should always be created outside of the React component (or the render method in case of class components). Your current solution creates a new React component on every render, that's why all child components are destroyed and re-created (unmounted + mounted). It's not related to Jotai but can be reproduced withuseState()
as well.Just create the styled component outside: