Hacker News new | ask | show | jobs
by gernb 1249 days ago
This biggest issue I have with React is that I always feel like I have to re-write my model to use it. I've already got a model, now I want to add a UI. I try, and at least for me, React doesn't like it.

A simple example might be a tree structure. Think of folders and files on your computer. So first I go implemented a file system and I have folders that are a collection of files and folders. This data structure is hierarchical.

Now I want to make a React based UI where the user can create and delete folders and files.

5 folders deep the user want's to add a file. According to all the react docs I'm not allowed to just add a file to that folder as that would be mutating data. Instead I need to make a new folder, copy all the old entries to it, put the new file in. But, since it's 5 level deep subfolder, by the same rule, I need to do the same with its parent (make a new parent, copy all the old entries except the old folder, put in the new folder that's holding the new file). Oh but we're 5 levels deep so repeat all the way up the tree.

React people will often say "flatten your data" but that's the entire point, I shouldn't have to change my model to satisfy the UI library! I've already got working code without a UI. I just want to add a UI, not re-write all the other non-UI code.

I'm sure I just don't get it. Maybe a react expert will tell me how I use react without having to change my model.

2 comments

Nothing in React (or any reactive language/library) prevents you from doing that. But if you're going to mutate state, make sure to notify it about it. Add an entry to your data ? Sure, just re-do a setState() after and you'll be good. But that requires you to make sure that every time you mutate state, you re-notify the UI of it.

    setState(data.map { d-> d.tree.map { d2 -> ... } })
is the exact same thing as

    data[5][6][2][4].addChild(file)
    setState(data)
React people will tell you to only use immutable objects, do copies, etc, but if your usecase requires mutating data, just mutate the damn data. It's not all or nothing. And even if you want to work with purely immutable data, you can work with lenses and have everything you want. With any language that has proper typing, you don't even need to build lenses with "keyed" names and can get the proper types.
If you're using class component, you can mutate the state then manually trigger force (UI) update