in Code

Quick Tip: Reduce some common React boilerplate

If you’re keeping track of a presentational component’s visibility in state, then you normally need to set up an initial state in your constructor and set up click handlers to deal with toggling that visibility. But through the clever use of some ES2015 features, you can get rid of a lot of the overhead you need to construct this. Check out this example:

Pretty neat! That knocked this example component’s size down to about half of the other one. We use the fact that the initial state is falsey if it hasn’t been set to read from a default object. We also use an inline arrow function to toggle the visibility state, rather than extracting it out to a full class method.

This won’t scale if you’re needing to read from state in multiple methods. Nor will it scale if you need your toggle button to do other things. However, for simple components, this can keep you from having to type out as much code as before, which reduces complexity and increases readability when you go to a code review.

Leave a Reply

  1. Neat idea with the default state part.

    In case you haven’t realized this already, but putting arrow functions in your render will create a new function every time.

    > Bind event handlers for the render method in the constructor. eslint: react/jsx-no-bind
    > A bind call in the render path creates a brand new function on every single render.
    https://github.com/airbnb/javascript/tree/master/react#methods

  2. In your case, the OR operation will always be true and toggling won’t occur.

    Bitwise OR
    —————-
    1 = 0 || 1
    1 = 1 || 0
    1 = 1 || 1
    0 = 0 || 0
    —————-

    – onClick={() => this.setState({ show: !show })}
    — Will allow you to toggle based on state.

    Rad code reduction otherwise