React recreates my component on each material ui tab switch

wat*_*ery 6 javascript tabs reactjs material-ui

I added a Material UI Tabs component in my application, coding it almost similar to the one in their Simple Tabs demo.

I'm experiencing, though, that the components inside each tab — that is those at:

render() {
    /... 
    {
        value === 0 && < MyComponent1 / >
    } {
        value === 1 && < MyComponent2 / >
    } {
        value === 2 && < MyComponent3 / >
    }
    /...
}
Run Code Online (Sandbox Code Playgroud)

are being recreated (I can trace this with a console.log() in their constructor) each time I switch tab losing their state, while I'd expect them to just be unmounted and remounted.

Am I doing something wrong or is that the normal behaviour?

Chr*_*ore 7

This is the expected behaviour for a component. Before it gets mounted, the constructor gets called. It might be worth giving the docs a re-read if you are unsure of the flow

https://reactjs.org/docs/react-component.html#constructor

If you want to components to keep state whilst it gets hidden/shown, you can pass through a flag (or className) which indicates whether to hide the component or not.

render() {
  /... 
  < MyComponent1 hidden={value === 0} / >
  < MyComponent2 hidden={value === 1} / >
  < MyComponent3 hidden={value === 2} / > 
  /...
}
Run Code Online (Sandbox Code Playgroud)

The component can then use the prop to update what get's shown whilst still retaining state. e.g. you could add a class which hides it with css.