Search This Blog

Wednesday, December 14, 2016

On spaghetti data structures and how React changed the way i think about them

I got started with ReactJS a few months ago, and I'm Lovin' It. From the get-go, you have to think in terms of components and one-way data flow. It makes it a little less convenient for "just hacking around" and making something, but that's OK; i'm using it for a big project.

In React, data flow is single-direction, from parent components to children. And if you're using Redux, there's a single state object that is the source of all data. In a diagram, it looks like this:

My previous big project ( does not use React. You have various components storing their local state in various ways, mainly <input> value, selected radio button, and jQuery data. The data flow looks kind of like this:

It's awful!

You have certain options that are only available when other options are selected. There's one spot where there are two places to do the exact same thing, so the elements have to mirror each other.

When i began the project, it wasn't so complex. I thought a simple HTML <form> with a bit of JS magic would be enough. (I also didn't know better.) But as the project grew, the requirements became more complex, and i just kept patching the code.

A few months ago i had to build a system to save and load the state. (This was still before learning React.) At that point i was able to basically just serialize the form to JSON and then load those values. Last week there was an urgent bug that some options weren't being saved (hadn't been needed till now). The problem is, some of these options are lists of text inputs. Others are radio buttons. Others are lists of checkboxes. Still others are plain text inputs or checkboxes. I patched the system (again) to save the rest of the options, but it's not clean at all.

I just talked about saving and rehydrating the state, but it's even more of a pain to actually use those options. The webpage is just a frontend for sending data to the backend, but it still has to pick which <input>s to send.

It would be much nicer everywhere if it could just have a single object that's the source of truth for the webpage. If i have the time, i'll do exactly that. I probably won't actually use React for this, but i will use the lessons it taught me.

No comments:

Post a Comment