Search code examples
reactjsthisstatefluxreactjs-flux

Reactjs - Using "this" in components - should it be avoided at all times?


In a nutshell

After using React for a few months - the idea of using this to keep track of changing variables in a component has come to feel like snorkeling in the North Pole - no one should do it,ever.

But with Leaflet that is kind of what happens(and for details I'll skip, I can't use the really sweet leaflet component wrapper that now exist.

The problem that lead me to this:

I'm trying to save the initial zoom level into a store as state, but since I'm using an Action that changes the rendering path the opens the Map Component I can't call another Action as the MapComponent mounts without getting a chain Action error "Invariant Dispatch". I also couldn't find any async updates to zoom in the Leaflet Docs to get around the synchronous Actions error.

Without the initial zoom I can't see if the first zoom the user makes is up or down :(

My Hack Solution:

Since the rest of the map is saved in this I just created another property of this called this.currenZoom that gets initialized as the component mounts and updated when zoomStartis called.(technically updates like state)

My Question:

Am I snorkeling in the North Pole using this to keep my zoom state? Or is that acceptable since Leaflet technically isn't working with the virtual DOM the same way? Is using this okay to manage variable updates in some cases in our components.

Note: This question might come of as peevish, but seriously I've went so long using state and props for everything that it just feels MEGA hacky using this in my components.


Solution

  • I do think it's fine to keep data directly on this if and only if it doesn't affect rendering (although I wouldn't do so unless there's a good reason not to simply put it in the component's state). The render method should always be a function of this.state and this.props (and only those two things).

    Doing this is most often used as an "escape hatch" mechanism--like the scenario you mention here--where some library, plugin, or function doesn't interact with the virtual DOM in the same way as a normal component.

    You can even see the React documentation using this method in the SetIntervalMixin mixin example:

    var SetIntervalMixin = {
      componentWillMount: function() {
        this.intervals = [];
      },
      setInterval: function() {
        this.intervals.push(setInterval.apply(null, arguments));
      },
      componentWillUnmount: function() {
        this.intervals.forEach(clearInterval);
      }
    };