React Gotchas

By Dave Ceddia

React Gotchas

React is an intuitive library, for the most part. Draw boxes around your UI designs and you’ve basically got your component structure laid out. JSX is nice to write and keeps the boilerplate down.

But there are a few stumbling points where I’ve seen people get stuck (and gotten stuck myself). Internalize these few rules and you’ll avoid some strange errors.

Capitalize Component Names

If you’re using JSX (and most people are), the components you write must begin with an uppercase letter. This means using names like UserList and Menu and SubmitButton, and not using names like userList, menu, and submitButton.

In JSX, a component that starts with a lowercase letter is assumed to be a built-in HTML or SVG element (div, ul, rect, etc.).

Earlier versions of React kept a “whitelist” of all the built-in element names so it could tell them apart from custom ones. Maintaining that whitelist was time-consuming and error-prone – if a new SVG element made its way into the spec, you couldn’t use it until React updated that list. So they killed the list, and added this rule.

If you’re not using JSX, you can get away with writing components that start with a lowercase letter. Beware that it’ll hurt reusability outside your project, though.

Close Every Element

JSX requires that every element be closed. This includes the ones you might be used to leaving open, like <br> or maybe <input>.

DO THIS:

return <br/>;
return <input type='password' .../>;

NOT THIS:

return <br>;
return <input type='password' ...>;

setState is Asynchronous

I didn’t notice this when I started out with React. The setState function is asynchronous!

If you call setState and immediately inspect this.state, chances are it will not be updated yet.

If you need to set the state and immediately act on that change, you can pass in a callback function like this:

this.setState({name: 'Joe'}, function() {
	// called after state has been updated
	// and the component has been re-rendered
});

Another alternative is to use the componentWillUpdate or componentDidUpdate lifecycle hooks, which will be called immediately before and after rendering in response to your state change. They’ll also get called whenever props change – so if you absolutely want to respond only to state changes, use the callback approach.

Wrap Up

So that’s 3 things to watch out for in React. Know of any more? Help us avoid them by posting a comment!