Patrick’s Blog — Web development

10 habits I borrowed from python that I use in React (Part I)

Best practices that I believe should carry over from python to JavaScript, specifically in React

Patrick Da Silva

--

Do you see the similarities between my python code and my JavaScript code? (Image source: self-made.)

I began my career as a developer and data scientist by using python as a language, which led me to adopt certain practices that I thought were extremely relevant as a programmer. This idea might be controversial for some JavaScript developers, but I think we have a lot to learn in JavaScript (and in my case, especially in React) from python! Those practices are very well summarized in the Zen of Python:

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

I came to write this article because I came across the Zen of Python while talking to my colleagues, and it made me realize how much of my JavaScript habits came from subconsciously following my habits that came from the Zen of Python. I believe it has gotten a lot of ideas right that should be used in any language!

Choose your variable names carefully (Beautiful is better than ugly)

It’s easy to name a component “Container” or “Wrapper”. But that makes naming conflicts really hard to figure out, and more technically, it really annoys someone doing a search through the repository to see where are the other instances of that “Wrapper” for a search-and-replace task. Giving a more specific, context-relevant name to a variable makes it easier to read and to work with. Give it some thought!

Make your code as obvious as possible, but don’t exaggerate (Explicit is better than implicit)

One way that I like to do this (that aligns with the previous point) is to use the power of React Hooks that allows us to isolate functionality. One problem that always shows up is tracking some binary object, which can easily be done with a boolean. So what do you always end up doing? useState. It looks something like this:

An example of a perfectly valid use of useState to track some binary state.

But “True” and “False” are internal logic states, they’re not very expressive in terms of what the ExampleComponent is supposed to be used for, so it’s not clear what “setSelectedTrue” means in terms of functionality when reading this code. One would have to read the code thoroughly to figure out what happens. One thing that I like to do is to isolate such logic into a hook:

The “useBoolean” hook is a very re-usable hook (that I use all over the place!) to keep track of a boolean state. One thing that you often end up realizing by doing such re-factorings is that by naming your variables properly, you realize that your code didn’t make sense as well! In the original case, you could have reasoned “well if my ComponentOne is selected, I want to render those two, and if it is not, I only render ComponentTwo”. But by re-phrasing “if my ComponentOne is shown, I show it, otherwise I don’t, but in any case I need to render ComponentTwo”, it becomes much more obvious that there is no need for ComponentTwo to be rendered the same way the same way each time, and it sounds better when you’re thinking about it.

The other nice thing about using custom hooks to re-use functionality and returning the results as an array is that if the callbacks in the array are generic enough, it becomes very expressive to be able to name them whatever you want, depending on the context. Notice how I used verbs like “show” and “hide” on a callback as simple as one that sets a boolean value. This makes code really obvious to the reader.

Working code isn’t enough: simplify your code! (Simple is better than complex.)

One typical of that is when I see the following happen in a React component: you work with a large component that has a lot of building blocks, you try to make something work, so you make props move around until you figure it out, and in the end, you see a situation like this:

Observe the very complicated process used just to inject the count in a template literal. It works, but…!

Why the useState? Why the useEffect? Maybe it made sense in the previous, messy, explorative state of the code, but it is certainly not necessary now! This would look much better:

See how the CountingButton component is much simple now without the useState and useEffect?

Of course, some people might come and say “don’t try to fix something that already works”, but the counter-argument is, “for situations like these, you’ll most probably break it next time you add a feature if you don’t simplify it. Your code will change, and you should always write as if it will! Commit your changes, try to simplify your code, test, and if it works, be happy that your code is more readable!

This problem can become even worse when some very complex CSS can achieve the same results as a simpler, shorter CSS code, where the complex CSS code only worked because half the lines were overwriting each other and changing the style of that component would have taken forever (and designers *love* to change designs… so it will happen sooner or later!). Simplify your code!

Don’t make complex things more complicated than they need to be (Complex is better than complicated.)

I think this one doesn’t need an example, it would be “too complicated”. If you’ve ever written anything in JavaScript, you’ve seen a codebase somewhere with a 1000 lines long script of meaningless repetitions with slight changes every 10 lines or so, where someone just didn’t bother to refactor. There are some rules that I try to follow to avoid very large and unreadable scripts in React/styled-components:

  • When writing a component, put your styled-components in a separate module. I tend to name the module for the component after the component, and the module for the styled-components “styles.js”, a bit like when CSS modules were in .css files and JavaScript in .js files. With CSS-in-JS, you can put both in the same file, but that just makes it harder to mentally separate concerns when reading and makes it more complicated to read.
  • Using the above rule, only put one component per module (not counting the styled-components). If you put more than one component in the same file and someone knows of a problem with one of the two components, how are they supposed to look for that component in your repository? If you name your module after one of the two (or more) components, then you can’t find the other one(s) easily (you could have to do a global search… imagine if your second component was always called “Wrapper!”). Having each component in its own file helps a lot when debugging! Sometimes the filename is all you can get!
  • Using the above rules, if you add a unit test in its componentName.test.js file, and maybe some stories via the fantastic Storybook library in a componentName.stories.js file, and some subcomponents that you put in their own files or even maybe subfolders next to your component… you quickly end up with a lot of files. So I do myself a favor and always default export my component in its file reserved for it, and when I need my component outside of its folder, I expose it to the rest of my repository through an index.js file. So creating a component ends up leading to a folder with a tree structure like this:
...
├── Button
│ ├── Button.js
│ ├── Button.test.js
│ ├── index.js
| ...
| ├── stories.js
| └── styles.js
...

where the … in the middle represents the potentially many subcomponents required to construct the Button component. (This would probably not happen with a Button, though!) I already hear some say, “why so many files for a Button? Put everything in one file except the unit tests!” and I answer, “why so many lines of code in one file for a collection of simple concepts? Isolate the concepts so I don’t have to see a very complicated bulk all at once!”

Use a 4-spaces indent to easily detect ‘callback hell’ (Flat is better than nested.)

Before I say anything, I am not getting in the eternal debate of tabs vs. spaces (I’m a tabs guy). My point is only about the width of such tabs/spaces.

‘Callback hell’, in this case, can be achieved by heavily nesting JSX tags (recall that JSX is syntactic sugar for React.createElement, so nesting JSX *is* producing callback hell!).

The simplest trick to avoid callback hell is to isolate concepts in your heavy nesting of function calls and convert it into a function that’s less nested and easily readable. And that’s exactly what you should do! Instead of cramming your whole app in one big JSX file, you isolate concepts as components, even if you re-use them only once; the ability to test them separately is a good enough reason to want to break down a big component into smaller ones.

So the question is: when is nested ‘too nested’ and should be flattened with this technique? There is no right answer to that, but using 2 spaces of width for indentation makes the discussion uselessly longer. Use 4 spaces indentation, and then it’ll become obvious!

Last note on this: un-nesting your heavily nested React components also helps avoiding code to become ‘complicated’! Most of the time you’ll have a little bit of logic associated to each part of your big component, and by isolating a part of your big component as a smaller, ‘simpler’, more re-usable component, you’ll move the bit of logic with it, and make everything more ‘readable’. Do you see how all the tips fit together? It’s as if you couldn’t do one without the other!

Stay tuned for Part II, which will describe 5 more habits I borrowed from my learning experience in python!

--

--

Patrick Da Silva

CTO @ Staiy | Accelerating the transition towards sustainable fashion