Some ESLint rules to better your React code

ESLint is a tool for analyzing your JavaScript code and finding potential problems. A couple months ago I taught myself how to create plugins for it so I could write my own linting rules. I wound up writing two rules, both of which I’ll go into below.

prefer-use-state-lazy-initialization

React has a neat optimization trick for its useState hooks. When doing something like this:

const [data, setData] = useState(expensiveFunctionCall());

You’ll wind up calling expensiveFunctionCall on every render, when all you really wanted was to call it on the first render. To resolve this, React allows you to pass an initializer function to useState rather than an actual value:

const [data, setData] = useState(() => expensiveFunctionCall());

Now expensiveFunctionCall will only be called on the first render.

I was honestly pretty surprised that you could do this, and it’s such a neat little trick that I thought there should be a linting rule that would detect function calls in useState and alert you to using this optimization… and that’s what this rule does. If you’re not taking advantage of this trick, it’ll alert you so that you can change your code to do so.

I thought the rule was cool enough to submit to the React team, but it’s been languishing for months in their PR queue so I don’t see it getting added to their set of eslint rules.

no-named-useeffect-functions

There are a lot of coding tips out there, and not all of them are good. One such tip is naming useEffect functions. On the surface this might seem harmless, but it bloats the code, puts naming any kind of callback into question (for consistently), and is just in general pretty obnoxious. Now you may not agree with me, but if you do and want a rule to find such cases, well, this is that rule.

Only 2?

Yeah, for now at least. 

Is it easy to write these things?

If you’ve ever wondered about how to write your own eslint rule, just check out the project for the rules above. They’re surprisingly easy to write. Once you have the basic boiler plate down, all you really need is an AST Explorer and you can write them pretty quickly (this generator is also pretty useful).

Leave a Reply

Your email address will not be published. Required fields are marked *