@procore/react-state-patterns
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

Logo

react-state-patterns

Tiny utility package for easily creating reusable implementations of React state provider patterns.

🚀 @procore/react-state-patterns makes it easy to (and reduces boilerplate) create implementations of common React state provider patterns.

⚠️ Powered by React Hooks under the hood. (This library has a peer dependency on react: >= 16.8.0)

Why?

react-state-patterns is incredibly simple, small, and lightweight — making it a great choice for applications that wish to keep their footprint small and do not want a complex state management solution. This library is also great for those that wish to utilize React Hooks for reusable state but do not want to couple their presentational components directly with state (this makes unit testing components much easier 🌟).

react-state-patterns also makes state management modular — increasing code clarity and making organization of state a breeze 🍃.

Getting Started

Install

npm install @procore/react-state-patterns --save

Usage

API

View API Docs Here

Creating State Patterns

Directly From Hook

import useProviders, { hookSchema } from '@procore/react-state-patterns';

// Create the state patterns
const Counter = useProviders(props => {
  const [count, setCount] = useState(props.initialValue || 0);
  const handlers = {
    incrementBy: value => setCount(count + value),
    decrementBy: value => setCount(count - value)
  };
  // hookSchema(...)
  //    => { counter: { state: { count: 0 }, handlers: { incrementBy: (v) => {...}, decrementBy: (v) => {...} } } }
  return hookSchema({ count: count }, handlers, "counter");
});

// Counter = { useHook, withState, State, Provider, Consumer }

Using useStateHook util

useStateHook API Docs

import useProviders, { useStateHook } from '@procore/react-state-patterns';

// Create the state patterns
const Counter = useProviders(
  useStateHook(
    (props) => ({ count: props.initialValue || 0 }),
    {
      incrementBy: state => value => ({ ...state, count: state.count + value }),
      decrementBy: state => value => ({ ...state, count: state.count - value })
    },
    "counter"
  )
);

// Counter = { useHook, withState, State, Provider, Consumer }

Use the patterns

Decorator Pattern

const Displayer = ({ counter: { state, handlers }}) => (
  <React.Fragment>
    <div>{state.count}</div>
    <button onClick={() => handlers.decrementBy(1)}>Decrement</button>
    <button onClick={() => handlers.incrementBy(1)}>Increment</button>
  </React.Fragment>
);

const StatefulDisplayer = Counter.withState(Displayer);

const rootElement = document.getElementById("root");
ReactDOM.render(<StatefulDisplayer initialValue={5} />, rootElement);

Edit React State Patterns (Decorator)

Render Prop Pattern

const Displayer = (props) => (
  <Counter.State initialValue={5}>
    {({ counter: { state, handlers } }) => (
      <React.Fragment>
        <div>{state.count}</div>
        <button onClick={() => handlers.decrementBy(1)}>Decrement</button>
        <button onClick={() => handlers.incrementBy(1)}>Increment</button>
      </React.Fragment>
    )}
  </Counter.State>
);

Edit React State Patterns (Render Prop)

Context Provider/Consumer Pattern

const Displayer = (props) => (
  <Counter.Provider initialValue={5}>
    <Counter.Consumer>
      {({ counter: { state, handlers } }) => (
        <React.Fragment>
          <div>{state.count}</div>
          <button onClick={() => handlers.decrementBy(1)}>Decrement</button>
          <button onClick={() => handlers.incrementBy(1)}>Increment</button>
        </React.Fragment>
      )}
    </Counter.Consumer>
  </Counter.Provider>
);

Edit React State Patterns (Provider/Consumer)

Custom Hook Pattern

const Displayer = (props) => {
  const { counter: { state, handlers } } = Counter.useHook({ initialValue: 5 });

  return (
    <React.Fragment>
      <div>{state.count}</div>
      <button onClick={() => handlers.decrementBy(1)}>Decrement</button>
      <button onClick={() => handlers.incrementBy(1)}>Increment</button>
    </React.Fragment>
  );
};

Edit React State Patterns (Custom Hook)

Code Style Guides

code style: prettier

Prettier is run as a pre-commit hook to automatically modify staged .js and .jsx files to adhere to base code style rules defined in the .prettierrc.

Eslint is also used as an in-editor linter, so be sure to install an appropriate Eslint Plugin for your editor of choice. Prettier rules are setup to take precedence and override any conflicting eslint rules.

Package Sidebar

Install

npm i @procore/react-state-patterns

Weekly Downloads

5

Version

1.0.0

License

MIT

Unpacked Size

15 kB

Total Files

4

Last publish

Collaborators

  • alyelashram_procore
  • melch-procore
  • peterknif
  • moaz-ashraf
  • attachi
  • a.elbadawei
  • hyogman
  • dmitri_wm
  • stephanie.brereton
  • procore-oss-user
  • stevenkang3
  • max.helmetag
  • codyrobertsprocore
  • miguel.garcia-procore
  • magdyyx
  • atoaima
  • mustafa-abdelrahman
  • elewando-procore
  • ahmed.ghorab
  • lnspatz914
  • richard.bunn
  • omar.wagdy
  • mona.khairbek
  • mbartlett413
  • cody_schindler_procore
  • yoasyo25
  • ritchlee
  • andersontr15
  • steven.hinkle
  • jamie-dugan-procore
  • hgouhierprocore
  • denzylbalram
  • sarah.freitas
  • alan.bresani
  • amyprocore
  • yoyis3000
  • elijah.procore
  • mike-arndt-procore
  • jnhoang1
  • pam-whisenhunt
  • shradha.khard
  • david-christensen-procore
  • javio-procore
  • chance.eakin.procore
  • gideon-procore
  • ihor.diachenko_procore
  • justinmwatts
  • tedyang
  • jyang-procore
  • pwhisenhunt-procore
  • fairchild
  • rodayna.ehab
  • neil1023
  • scottstern
  • brian.smith1
  • g2mitchell
  • dlameter-procore
  • kylepietz
  • abhijit-procore
  • lhuang325
  • jake-pitkin
  • erikthoreson
  • simona.iancu
  • decha-sanson
  • aberkowitz
  • asamay
  • mustafa-u-abdelrahman
  • rajatmenhdiratta
  • jacksonleach-procore
  • pmfrawley
  • phunguyen-pcor
  • tatsiana.clifton
  • deiab
  • srichaitanya.peddinti
  • kenny.foisy
  • matheusprocore
  • jgreene_procore
  • hectorthiele
  • etokarev
  • daniel.ferreira-contractor
  • dmccraw-procore
  • cyrille.bai
  • greg.sparks
  • fabiomelo513
  • phil.custer
  • bbreyel921
  • amir-iskander
  • neil.mckeeman
  • nickprocore
  • lzhou888
  • davidshure
  • stevenliprocore
  • ramysaid2
  • refaiepcn
  • jgentes
  • faraz.hanif
  • mostafaeltazy
  • agamaleldin
  • andrew.isaac
  • saranahal2
  • rodrigo.dejuana
  • kellen.stewart
  • bill-wagner
  • ezrasimeloff
  • jeffgiaquinto
  • gturkadze
  • sean.spearman.procore
  • kylemartinez-procore
  • roobo-romeski
  • andres-mendez-procore
  • gaurav.sharma.procore
  • tracy.otto
  • sarah.heredia
  • victorbendeck-pc
  • cbathgate
  • davidkangpro
  • kyle.liu
  • amin.jaipuri
  • grafffffff
  • mishaelowoyemi
  • evan.cerwonka.procore
  • ilya.dryha-contractor
  • varomir
  • yogevfine1
  • timofeee
  • matt.harris0223
  • winson.chu
  • andersonbispoprocore
  • scorgiat-procore
  • ladavarga
  • procore_halzy
  • enyaga
  • willpankonien
  • sateesh-kadiyala-procore
  • chris.berber
  • txin1
  • epalinprocore
  • mehrdad-panahandeh
  • tyler.wasden.procore
  • jeremy.lund
  • dineshkumar.jayak
  • ryanfuentesprocore
  • stajics
  • brocktillotsonprocore
  • kyle.williams
  • dtorres-procore
  • noor.ali
  • ari-procore
  • alanprocore
  • jl4ever
  • james.lawson
  • ajaykumar-procore
  • dennis.heckman
  • tara.chambers
  • lalovar-procore
  • james.cleary
  • chadryder
  • devin.cunningham.procore
  • abhijit.patwardhan
  • lydiahara
  • sherylnapigkit
  • changprocore
  • apcarroll_procore
  • andy.mayer
  • bob.laskowski
  • vinaya-procore
  • kahliholmes
  • andrew.wheeler
  • leandro-proc
  • yadhu.prakash
  • jason-kaye
  • jesse.olsen
  • patrick.lardin
  • brad.urani
  • allenanle.procore
  • brookyboy009
  • uddhavjoglekar
  • dancingshell
  • rysmithprocore
  • robbiegprocore
  • jadamsss
  • jeremy.bouzigard
  • timdoherty
  • b.bookout
  • jalyng
  • htael
  • dev-account-admin
  • sseanwang
  • bhargavrnd
  • farismmk
  • dannyporrello
  • danny.ou
  • messanjah
  • eyvettesou
  • jgee67
  • cagmz
  • mariah_delaney
  • lukenispel
  • kimhin267
  • juliana.hernandez
  • judy-lu-pc
  • procore-it-support
  • andrewburke-pc
  • jkleintech
  • rachel.arkebauer
  • procore-npm-bot
  • james.dabbs-procore
  • laurenbrandsteinprocore
  • scottbieser-procore
  • zach.mckenzie.procore
  • shayonj_procore
  • heplayskeys
  • mike.south
  • thomasoboyle
  • dischorde
  • derek-carter-procore
  • dlgasser
  • cfprocore
  • evan.waits
  • jeremy-marcus
  • jmejia-fsl
  • ersgonzalo
  • stephan-procore
  • aleclarsenprocore
  • yihai.zweifel
  • jay-rajan
  • jacky-lei
  • peter.jin