mavili
mavili

Reputation: 3424

React Router calls component constructor when switching routes

I'm using react and react-router for a SPA which has a navigation. The router is calling the react component 'constructor' every time a navigation item is switched. Here is the relevant bit of code:

class Home extends React.Component {
    constructor(props) {
        super(props);
        console.log('component constructed!');
        this.state = {
            counter: 0
        }
        setInterval(() => this.setState({
            counter: this.state.counter+1
        }), 1000)
    }

    render() {
        return (
            <h3>Counter: {this.state.counter}</h3>
        );
    }
}

ReactDOM.render(
    <Router history={hashHistory}>
        <Route path="/" component={App}>
            <IndexRoute component={Home} />
            <Route path="profile" component={Profile} />
            <Route path="settings" component={Settings} />
        </Route>
    </Router>,
    document.getElementById('container')
);

Every time I switch from one tab to another, the counter starts from 0. Obviously I understand that render() should be called every time its state changes or when router switches tabs, but why call constructor for change of tab?! Is that how react-router works, or am I doing something wrong?

This question has been asked here, but the accepted answer talks about 're-rendering' and not re-construction of the component.

Upvotes: 4

Views: 4041

Answers (1)

Paul S
Paul S

Reputation: 36787

The constructor is called every time that a component mounts. Each time that you navigate to the location /, the <Home> component will mount. When you navigate to another location, the <Home> component will unmount. If you want the state to be persistent across navigation, it should be kept higher up the tree.

Upvotes: 6

Related Questions