News for hackers. Stuff that matters.
Re:Persisting React State in LocalStorage by geocar on Friday February 28, 2020 @01:11PM (#22444892)
I'd recommend just putting this crap in the URL. That way (a) the server could see it too, and (b) users could share their state by sharing the URL (which makes supporting them easier!). If you've got so much state this doesn't make sense, then ¯\_(ツ)_/¯ I suppose caching it in localStorage is fine, but I haven't yet run into this problem.

Having a setSticky((k,v) => that modifies the url with the history API is pretty easy, and if you get the results using the Context API, you can have your root monitor the URL (again using the history API) and publish the result using a context so you don't have a storm of updates.

Re:Persisting React State in LocalStorage by k__ on Friday February 28, 2020 @01:58PM (#22445301)
User specific state like "dark mode enabled" would probably be better inside localStorage than inside a shareable URL.
Re:Persisting React State in LocalStorage by hinkley on Friday February 28, 2020 @04:38PM (#22446650)
Disagree.

There are whole classes of UI errors that are only reproducible if you use the same look and feel as the customer. Black text on a black background being reported as data loss or missing functionality, for starters, but there are many others.

Re:Persisting React State in LocalStorage by Dylan16807 on Saturday February 29, 2020 @01:47AM (#22449322)
That's useful in the specific case of debugging but as a user it would be pretty awful if all my customization disappeared every time I clicked a link from another user.

And you want screen resolution and DPI too for a proper "same look and feel" debugging experience. Which you could always hide in the URL if you want, but you shouldn't act on it by default. Do the same thing with UI settings, if you must. Include them but don't act on them.

Re:Persisting React State in LocalStorage by hinkley on Saturday February 29, 2020 @10:25AM (#22450979)
That can also be achieved by storing that information as user preferences on the backend, and it won’t affect your friends but let’s support people figure out what they need to know.
Re:Persisting React State in LocalStorage by geocar on Friday February 28, 2020 @03:25PM (#22446002)
Don't browsers have media queries for things like that?

I think some old browsers didn't, so I guess that's why there are all those tacky switches on blogs these days, but I don't usually worry about obsolete things like "made for netscape 4" banners...

I also think for an application, I'd much prefer my settings on the server so I can get them again when I'm using another device.

Re:Persisting React State in LocalStorage by bobthepanda on Friday February 28, 2020 @03:32PM (#22446062)
Compatible with everything except IE 11, but in draft: https://developer.mozilla.org/en-US/docs/Web/CSS/@media/pref...
Re:Persisting React State in LocalStorage by ultrarunner on Friday February 28, 2020 @03:37PM (#22446111)
We have an application that's used outdoors day and night in some cases. The good news is it makes a ton of difference in usability; the bad news is I honestly still have to search for instructions on toggling dark mode on Ubuntu. The switch is a lot simpler.
Re:Persisting React State in LocalStorage by geocar on Friday February 28, 2020 @03:55PM (#22446280)
Hey go nuts. Whatever works for you.

But if you wanted to use other applications that didn't have such a switch, you might consider looking into a hotkey or an extension. I found this[1] after a quick ddg. Maybe it'll help?

[1]: https://extensions.gnome.org/extension/2314/dark-mode-switch...

Re:Persisting React State in LocalStorage by k__ on Friday February 28, 2020 @04:23PM (#22446499)
Sure, it was just an example. :)
Re:Persisting React State in LocalStorage by geocar on Friday March 06, 2020 @11:30AM (#22504864)
I figured as much, but I feel pretty strongly that every piece of state needs to be accessible to a user or to the server, otherwise you lose control of it and that can war on.

I know that for performance reasons, or for privacy reasons, or even for time/effort reasons, that's not always possible, but I'm also always genuinely hopeful that there's some new class of data out there that doesn't fall into that (general) rule.

Re:Persisting React State in LocalStorage by joshwcomeau on Friday February 28, 2020 @01:28PM (#22445050)
That's a neat idea!

In the case of something like a blog, though, you anticipate folks sharing the URL. It'd be kinda strange to inadvertently share persisted settings (or worse, stuff that's maybe a little personal)

Re:Persisting React State in LocalStorage by geocar on Friday February 28, 2020 @03:30PM (#22446042)
What kind of persisted settings?

Surely those things should live in the application, no?

Other things like blog gadgets to choose different themes (or whatever) probably should live in the URL to facilitate bug reports! I think Internet users are savvy enough to remove that stuff from a URL when sharing on HN (and if not, the mods seem to).

Also, I think it's pretty clear I'm talking about navigation and queries in the above though, just so there's no other confusion: I definitely suggest continuing to use setState or ref for input boxes!

Re:Persisting React State in LocalStorage by rbalicki on Friday February 28, 2020 @02:25PM (#22445535)
There should be a single useState hook which takes an optional `{persistor, reader}` param. Then the choice of whether to stuff this in local storage, URL, local state, global (transient) state, post it to an endpoint, etc is all configurable depending on the use case.
Re:Persisting React State in LocalStorage by geocar on Friday February 28, 2020 @03:51PM (#22446252)
I've thought about something like that, but then what namespace would the keys belong to? Are they just some kind of hidden "superglobal" and if so, how do you reconcile the intention that state be limited to its component? On the other hand, you could (somehow) build unique symbols for each instance, then have the problem of who's responsibility is it to nominate friendly names for the query string (or yuck, __viewState!)? Or you could make it the persistor's [sic] responsibility; give it this, the key and the value, and let it worry about this exact same problem? Even if you choose one way, there's going to be people who want it a different way, so you've got to be right!

I think you really need setState to have some idea who might be interested in this state transition. One idea I had was to have an optional argument to specify the "Persistor" [sic], and then I consult the "Reader" in the constructor to build the initial (local) state, and in for own code, I ended up with something pretty much like that.

    this.setState({ fields, row: 0 }, UpdateURL)
where:

    setState(x,y) { return y&&y(x)&&super.setState(x); }
I haven't had any need for multiple "Persistors" [sic], nor any idea what multiple "Readers" might do, but you should find it easy to add a pub/sub mechanism in there if you needed it.
Re:Persisting React State in LocalStorage by nohuhu on Friday February 28, 2020 @03:59PM (#22446312)
This is what Statium and Urlito are for:

    import ViewModel from 'statium';
    import stateToUri from 'urlito';

    const defaultState = {
        foo: 'bar',
        qux: {
            time: Date.now(),
        },
    };

    const [getStateFromUri, setStateToUri] = stateToUri(defaultState, [
        'foo',
        {
            key: 'qux.time',
            uriKey: 'time',
            fromUri: time => parseInt(time, 10),
            toUri: time => String(time),
        },
    });

    const Component = () => (
        <ViewModel initialState={getStateFromUri}
            observeStateChange={setStateToUri}>

            {/* ... */}
        </ViewModel>
    );
Re:Persisting React State in LocalStorage by geocar on Friday February 28, 2020 @04:13PM (#22446421)
I'm not familiar with either of them, but that seems like a lot more code!

How does changing the URL trigger a state change? Does the whole page need to reload?

In my system, my "Reader" knows this object so it can just call the regular setState (I also have some mount/umount logic there to avoid leaking memory). This makes back/forward transitions very snappy!

I can also use the same logic for my Server (another "Persistor" [sic]) which indeed uses POST for submitting updates, but responses come down a shared SSE stream (which I need anyway so that users can see eachothers changes in real-time).

Re:Persisting React State in LocalStorage by nohuhu on Friday February 28, 2020 @04:43PM (#22446688)
> I'm not familiar with either of them, but that seems like a lot more code!

Sorry, I should have been more forthcoming with explanations but got paged at $work. Almost nobody is familiar with Statium yet, it's very new. :) It was developed for cloud applications UI here at DataStax.

Statium implements a very simple key/value storage in a React component called ViewModel. It is using `setState()` internally, so all the usual React rendering logic applies unchanged. Each ViewModel has access to keys of its ancestors, all the way up the chain. There is no global store but a chain of stores instead, which helps to keep state local to consumer components that use it.

Urlito is just a simple library for persisting state to and from URI, currently using query params. This is intended for local component state like selected tab, sort order in a table, or a list of expanded rows in a tree grid, the sort of things that do not deserve full blown URI routing pattern matching. We still use `react-router-dom` for that.

> How does changing the URL trigger a state change? Does the whole page need to reload?

No, it's the usual React logic: when ViewModel renders it will call the function provided in `initialState` prop, which in turn will read the current state of the model from URI query string. Whenever ViewModel state changes, `observeStateChange` function is called, and updates URI to reflect the current model state.

Urlito implements the functions for reading keys/values from URI and writing them back to URI, with support for default values and key filtering.

> In my system, my "Reader" knows this object so it can just call the regular setState (I also have some mount/umount logic there to avoid leaking memory). This makes back/forward transitions very snappy!

Almost the same solution in Statium, except that we have a full blown class based React component to hold the state, and hooks are not used internally (there is a hook based consumer API). The main reason for not using hooks for us is that the values held in `useState` are hard to propagate down the component tree, and hard to test. ViewModel takes care of this easily, with each key available anywhere downstream, e.g. a Component somewhere deep can retrieve the value of the topmost ViewModel without having to access it directly. This helps mightily with testing too: just wrap your tested components with a ViewModel and pass whatever you want to it (including state changes).

No memory leak issues at all, since a ViewModel is simply a React component that outsources `this.setState` for consumer components. :)

Transitions are very snappy with Statium, too. In fact, state updates are lighting fast: value updater function will walk up the ViewModel tree, find the closest owner and set the value in it using `setState`. This will cause the owner ViewModel and its children to re-render, but the render will be automatically scoped to the least amount of components. Since the state is usually localized, the problem of updating the whole app state on a keypress does not apply by default.

> I can also use the same logic for my Server (another "Persistor" [sic]) which indeed uses POST for submitting updates, but responses come down a shared SSE stream (which I need anyway so that users can see eachothers changes in real-time).

Asynchronous logic is hard to handle in synchronous React rendering paradigm... That was the reason for me to come up with a ViewController concept (https://github.com/riptano/statium#viewcontroller), which is the other part of Statium. The idea is to write business logic in a more imperative style, statements not functions:

    const loadUserPosts = async ({ $get, $set }) => {
        let [user, posts, comments] = $get('user', 'posts', 'comments');
    
        if (!posts) {
            await $set({ loading: true });
        
            posts = await loadPosts(user);
        
            await $set({ loading: false, posts });
        }
    
        if (!comments) {
            await $set({ loading: true });
        
            comments = await loadComments(user, posts);
        
            await $set({ loading: false, comments });
        }
    };
Decyphering this: $get is a function that returns ViewModel state values by keys, and $set allows updating these values. This is a matter of personal preference of course, but I think this approach makes the logic much easier to read and understand than Redux thunks or sagas.

There's also the RealWorld example app I came up with for React + Statium, check it out: https://github.com/nohuhu/react-statium-realworld-example-ap.... It's not yet submitted to the official list because I'm stuck trying to come up with a sensible logo for it... :)