immerjs / use-immer

Use immer to drive state with a React hooks
MIT License
4.04k stars 92 forks source link

support patches feature from `immer`? #73

Closed littlee closed 3 years ago

littlee commented 3 years ago

when using use-immer, I found that it no way to use the patches feature

import { useImmer } from 'use-immer';
import { enablePatches } from 'immer';
enablePatches();

const App = props => {
  const [a, setA] = useImmer({ a: 1 });

  return (
    <div>
      <pre>{JSON.stringify(a)}</pre>
      <button
        onClick={() => {
          setA(
            draft => {
              draft.a = 10;
            },
            () => {
              console.log('this is never called');
            }
          );
        }}
      >
        setA
      </button>
    </div>
  );
};

export default App;

but I don't really want to refactor all my useImmer to useState(produce)

mweststrate commented 3 years ago

We don't support patches in use-immer, to keep the package minimal and because patches have some potential issues like running side effects as part of a state updater. It's recommended to build your own utility hook around immer instead (feel free to take the source of this package as a base, it is pretty minimal)