npm.io
0.3.1 • Published 5 years ago

react-slice

Licence
MIT
Version
0.3.1
Deps
0
Size
16 kB
Vulns
0
Weekly
0

React Slice

A simple performant approach to state management in React.

  1. Uses reducers and dispatch
  2. Access state from anywhere with hooks
  3. You can still use statically
  4. Optimized for use with Typescript
  5. Full control of render performance
  6. 2kb minified

Demo

I've made a few Codesandboxes to play around with react-slice

Installation

npm i react-slice

The basics

Create a file and export your hook w/ reducer (fx counterSlice.js)

// counterSlice.js
import { createSlice } from 'react-slice'; // 👈👈👈

export default createSlice({
  reducer: /*👈👈👈*/ (state, action) => {
    switch (action.type) {
      case 'increment':
        return state + 1;
      default:
        return state;
    }
  },
  initialState: /*👈👈👈*/ 0,
  debugName: 'Counter', // Optional.
});

Then import that file somewhere else (fx App.jsx)

// App.jsx
import React from 'react';
import counterSlice from './counterSlice'; // 👈👈👈

export default function App(test) {
  const counterState = counterSlice.use(); // 👈👈👈

  const onClick = () => {
    counterSlice.dispatch({ type: 'increment' }); // 👈👈👈
  };
  return (
    <div className="App">
      <h1>{counter /*👈👈👈*/}</h1>
      <button onClick={onClick}>Increment</button>
    </div>
  );
}

And boom! That's all you need to get up and running!

Advanced/FAQ

Keywords