Search code examples
reactjsencapsulationinstance-variables

Recommended approach for storing state across instances of a React component?


What is the recommended approach (if any) for maintaining state across instances of a React component, while still keeping that state encapsulated in the component, so that it can't be accessed outside of the component?

My current approach, as I'm using CommonJS modules, is to use a module-level variable outside of the React createClass definition.

'use strict';

var React = require('react');

var mountCount = 0;

var MyComponent = React.createClass({
    getInitialState: function () {
        return {
            instanceNumber: mountCount
        };
    },

    componentDidMount: function () {
        mountCount++;
    },

    render: function () {
        return <div>I am instance no. {{this.state.instanceNumber}}.</div>;
    }
});

module.exports = MyComponent;

Is this recommended? If not, why not, and what would you recommend doing instead?


Solution

  • There's no recommended way; what you've done looks great.