DEV Community

Discussion on: React State Management in 2022

Collapse
 
phryneas profile image
Info Comment hidden by post author - thread only visible in this permalink
Lenz Weber

It is incredibly easy to break that library, as you can see in this codeSandbox: codesandbox.io/s/patient-waterfall...

const snap = resso({ count: 0, text: "hello" });

export default function App() {
  if (snap.count > 2) {
    /*
   as `snap.count` is accessed twice now, this breaks the rules of hooks:
   Warning: React has detected a change in the order of Hooks called by App. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks

   Previous render            Next render
   ------------------------------------------------------
1. useState                   useState
2. useMemo                    useMemo
3. useEffect                  useEffect
4. useState                   useState
5. useMemo                    useMemo
6. useEffect                  useEffect
7. undefined                  useState
   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    */
    return (
      <>
        now state {snap.count} is bigger than 2: {snap.count}
      </>
    );
  }
  return (
    <>
      {snap.count}
      <button onClick={() => snap.count++}>+</button>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nanxiaobei profile image
南小北 • Edited

Thanks for your testing!

Since need to let the component know which state is used, so for all situations, better deconstructing the state first and then use it.

fixed demo: codesandbox.io/s/resso-correct-usa...

function App() {
  const { count } = snap;

  if (count > 2) {
    return (
      <>
        now state {count} is bigger than 2: {count}
      </>
    );
  }

  return (
    <>
      {count}
      <button onClick={() => snap.count++}>+</button>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

And the usage code in resso's README has beed updated.

Some comments have been hidden by the post's author - find out more