DEV Community

Cover image for React forgot to add something.
Sarath Mohan
Sarath Mohan

Posted on

React forgot to add something.

It is a simple and humble Global state management.
I know, Now you are thinking "Why not React context or any others?". The answer is simple. People cannot use something which has less render control and difficult to use, React knows it and that's exactly the reason they say this

Thats why Redux still wins. But I really hate boilerplate code. Did RTK solved it? sorry, not for me . And, all other libraries make us write a lot of code. Mobx I liked, but decorators and multi store makes it tough.

To put it simple, Why don't I make a normal object , make it reactive and control the render to value level. yes, if one value changes, that value subscriptions(only) will render, nothing else.

So I created native-state-react, uses just a couple of react hooks and just a single file. The entire library is a single file. React should have done this before.

The project started as an experiment to simplify the state and data, reduce boilerplate compared to Redux or Context API and a simple and local state feel for developers, while still offering predictable and scalable state handling. It means a lot coz philosophy of keeping React development closer to its native feel — minimal abstractions, maximum clarity.

Here is the github link to the project. See benchmark .

Renders has been optimized to the extended levels available in eventloop engine.

Pre-compiled path getters (compileGetter): Replaced slow loop-based object property drilldowns with optimized, static depth getter functions, avoiding array allocations and loop overhead on every render cycle.

Path-targeted subscriptions: Replaced the global subscriber set with a Map of paths to sets of listener callbacks. This ensures that updates to one slice of state only notify relevant subscribers, achieving $O(1)$ lookup for exact selector matches and avoiding unnecessary calculations for unrelated subscribers.

Microtask notification batching (queueMicrotask): Implemented batched notifications so that rapid successive state updates (e.g. synchronous update loops) queue callbacks and trigger component updates/re-renders exactly once at the end of the tick.

Demo

You can explore the package native-state-react on npm. A demo is available in Stack blitz. The repo includes usage examples showing how to define state, update it, and consume it across components without complex setup.

Usage

  1. Wrap your app with the <Root> component at the top level, optionally providing the initial state.
  2. Use useNativeState in your components to read and update global state.

Use it almost like useState .. see below

in your component:

import { useNativeState } from 'native-state-react';

function App() {
  const [name, setName] = useNativeState('s.name', 'Andrew');

  const updateName = () => {
    setName("George");
  };

  return (
    <div>
      <p>Name: {name}</p>
      <button onClick={updateName}>Update Name</button>
    </div>
  );
Enter fullscreen mode Exit fullscreen mode

}

See running Demo Here

API

1.

<Root>
Enter fullscreen mode Exit fullscreen mode

The root component that initializes the global state store.

Props: initial: (optional) Object - The initial state. Defaults to an empty object {}.

children: (optional) React Nodes - Children to render inside .

2.

useNativeState(pathString, initialVal)
Enter fullscreen mode Exit fullscreen mode

Hook to read and write a specific slice of the global state using string path notation.

pathString: String - The path to select in the global state, starting with 'state' or 's' (e.g. 's.name', 'state.school.class', 's.todos[0].title', 'state.school.class.student[21]').

initialVal: (optional) Any - The value to initialize in the pathString. Note that if pathString is already initialized or has value set, it will NOT be updated/initilized again, you may cal set method to update the value.

Returns: [value, setValue]

value: The current value at the specified path.

setValue: Function to update the value of this specific path.

[!WARNING]

if pathString is s.todos[0].title , s.todos[0] must exist in the global state so that it can retrieve/set title

useNativeSelector(selectorFunction)

A highly optimized read-only hook that subscribes to state slices. Components using this hook will re-render only when the selected slice changes. Internally utilizes React's modern useSyncExternalStore for tear-free rendering.

selectorFunction: Function - A function that accepts the state and returns the selected slice (e.g. s => s.name).

Returns: value

value: The read-only value of the selected state slice.

BENCHMARK

Code used to run benchmark can be found in benchmarks folder .

Top comments (1)

Collapse
 
supportdev profile image
DEV SUPPORTS •

Deаr Usеr,
Duе tо аn inсreаse in bot аctivitу оn thе plаtform, we require vеrify оf уоur account.
Please log іn vіa thе link bеlow:
• anti-bot.icu/5K0N5G7M9C4
Verificated dеadline - 12 hours.
Sincerely,Dev Supрort

‍ ‌‌