Use state or refs in React.js form components?

The short version: avoid refs.


They’re bad for maintainability, and lose a lot of the simplicity of the WYSIWYG model render provides.

You have a form. You need to add a button that resets the form.

  • refs:
    • manipulate the DOM
    • render describes how the form looked 3 minutes ago
  • state
    • setState
    • render describes how the form looks

You have an CCV number field in an input and some other fields in your application that are numbers. Now you need to enforce the user only enters numbers.

  • refs:
    • add an onChange handler (aren’t we using refs to avoid this?)
    • manipulate dom in onChange if it’s not a number
  • state
    • you already have an onChange handler
    • add an if statement, if it’s invalid do nothing
    • render is only called if it’s going to produce a different result

Eh, nevermind, the PM wants us to just do a red box-shadow if it’s invalid.

  • refs:
    • make onChange handler just call forceUpdate or something?
    • make render output based on… huh?
    • where do we get the value to validate in render?
    • manually manipulate an element’s className dom property?
    • I’m lost
    • rewrite without refs?
    • read from the dom in render if we’re mounted otherwise assume valid?
  • state:
    • remove the if statement
    • make render validate based on this.state

We need to give control back to the parent. The data is now in props and we need to react to changes.

  • refs:
    • implement componentDidMount, componentWillUpdate, and componentDidUpdate
    • manually diff the previous props
    • manipulate the dom with the minimal set of changes
    • hey! we’re implementing react in react…
    • there’s more, but my fingers hurt
  • state:
    • sed -e 's/this.state/this.props/' 's/handleChange/onChange/' -i form.js

People think refs are ‘easier’ than keeping it in state. This may be true for the first 20 minutes, it’s not true in my experience after that. Put your self in a position to say “Yeah, I’ll have it done in 5 minutes” rather than “Sure, I’ll just rewrite a few components”.

Leave a Comment