Pomax / pomax.github.io

My blog, hosted via github
15 stars 1 forks source link

Re: React is just JavaScript #13

Open keb opened 1 year ago

keb commented 1 year ago

You likely already know this, but I figure it's important to mention, the reason a lot of React devs try to do everything the "React" way and send data back "up" to some injected global store is because it makes it easier to mock and test React applications this way, because everything remains contained within React and can easily be mocked using props or Providers, and the entire application state can quickly be replicated (including the status bar info without having to dispatch an event).

Your post does remind me of Mithril.js which has global state redraws by default, so having state defined outside your application is very natural, and the resulting app ends up looking very vanilla.

import m from 'mithril';

// global state in scope; tuck this in state.js and import wherever
const state = { num: 0 };

const actions = {
  increment() {
    state.num += 1;
  }
};

function App() {
  // local state via vanilla closures since the outer function only executes on mount
  let localVar = 'cool';

  return {
    view: () => (
      <div>
        <p>{state.num}</p>
        <button onclick={actions.increment}>increment</button>

        <p>{localVar}</p>
        <input type="text" oninput={({ target }) => localVar = target.value} />
      </div>
    )
  };
}

m.mount(document.body, App);
Pomax commented 1 year ago

Note that bundling makes no difference in whether or not you use a global store: the choice in whether to use Providers or localStorage (or any of quite a lot of solutions in between) is one of "what level of complexity do you need"? As long as its API makes "saving and loading state" easy, it doesn't matter, and that was really the main point of the post: you're never working in "React", your always working in JS, and what solutions you use to solve problems should be based on "I am working in JS, what can I do that is easy and maintanable" rather than "I am working in React, which React-specific solutions are there" and then ignoring the easiest, fastest, cleanest, etc. solutions because you forgot that "React" is not a programming environment, it's just a framework that slots into the larger programming environment.