react-immersive

Simple state management for react on top of immer

Usage no npm install needed!

<script type="module">
  import reactImmersive from 'https://cdn.skypack.dev/react-immersive';
</script>

README

react-immersive

Simple state management for react on top of immer

  1. Define the state.
  2. Define actions that will modify the state (it uses immer, so mutate it all you want).
  3. Use the hooks to access the state and actions.

Installation

Install via yarn:

yarn add immer react-immersive

Or npm:

npm install --save immer react-immersive

Usage

Pass your initial state as the first argument, followed by an actions creator on the second argument. An actions creator accepts a modifier function that lets you modify the state (I prefer to call it draftState) directly inside each of actions that you create.

Please head to immer's documentation if you haven't heard of it.

Initialization

todo.js

import { createContext } from "react-immersive";

const todo = createContext(
  { tasks: [{ task: "hello", done: false }] },
  (modify) => ({
    addTask: (task) => {
      modify((draft) => {
        draft.tasks.push({ done: false, task });
      });
    },
    removeTask: (index) => {
      modify((draft) => {
        draft.tasks.splice(index, 1);
      });
    },
  })
);

export default todo;

main.jsx

ReactDOM.render(
  <todo.Provider>
    <YourApp />
  </todo.Provider>
);

Accessing actions

import todo from "./todo";

const SomeComponent = () => {
  const actions = todo.useActions();
  const handleAddNewTask = () => {
    actions.addTask("Test");
  };

  const handleRemoveTask = () => {
    actions.removeTask(0);
  };

  return <div></div>;
};

Accessing state

useSelectState accepts a function that selects the state target, allowing your component to focus only on what matters.

import todo from "./todo";

const OtherComponent = () => {
  const firstTask = todo.useSelectState((state) => state.tasks[0]);
  return <div></div>;
};