ReactN
ReactN is a extension of React that includes global state management. It treats global state as if it were built into React itself -- without the boilerplate of third party libraries.
For support, reach out to us on the Reactiflux Discord channel #reactn.
💗 this project? Become a sponsor.
Install
npm install reactn
oryarn add reactn
Features
No boilerplate
For function components, import { useGlobal } from 'reactn';
to harness the
power of React Hooks!
For class components, simply change import React from 'react';
to
import React from 'reactn';
, and your React class components will have global
state built in!
If you prefer class decorators, you can continue to
import React from 'react';
for your components and additionally
import reactn from 'reactn';
for access to the @reactn
decorator!
Intuitive
Function components
Global state in function components behaves almost identically to local state.
You use [ global, setGlobal ] = useGlobal()
to access the entire global state
object.
You use [ value, setValue ] = useGlobal(property)
where property
is the
property of the global state you want to get and set.
Global reducers in function components behaves almost identically to local reducers.
You use dispatch = useDispatch(reducerFunction)
to mimic the behavior of
useReducer
, where instead of providing an initial state, the state of the
reducer is the ReactN global state object.
You use dispatch = useDispatch(reducerName)
to use a reducer that was added
by the addReducer
helper function.
You use dispatch = useDispatch(reducerFunction, property)
or
[ value, dispatch ] = useDispatch(reducerFunction, property)
to apply a
reducer specifically to a global state property. This is very similar to
React's native useReducer
functionality.
Class components
Global state in class components behaves exactly like local state!
You use this.global
and this.setGlobal
to get and set the global state.
You use this.dispatch.reducerName()
to dispatch to a reducer that was added
by the addReducer
helper function.
The @reactn
decorator allows you to convert classes that extend
React.Component
to ReactN global state components.
Map state to props
If you prefer Redux's connect
functionality, pure functions, or are dealing
with deeply nested objects, a
withGlobal
higher-order component is also available.
Table of contents
- Install
- Features
- Getting started
- Known issues
- Terminology
- Frequently asked questions
- Support
Getting started
Managing multiple states
This README is for managing a single global state. This is ideal for most applications. If you are using concurrent server-side rendering or otherwise want to work with multiple global states, follow the README for the Provider component, which allows you to limit a ReactN state to a React Context.
If you are unsure whether or not you need multiple global states, then you do not need multiple global states.
Initializing your state
You can initialize your global state using the setGlobal
helper function. In
most cases, you do not want to initialize your global state in a component
lifecycle method, as the global state should exist before your components
attempt to render.
It is recommended that you initialize the global state just prior to mounting
with ReactDOM
.
;;; // Set an initial global state directly:; ReactDOM;
TypeScript support
ReactN supports TypeScript out of the box! It is written entirely in TypeScript. This gives it powerful intellisense, auto-complete, and error-catching abilities.
TypeScript can maintain inferred global state and reducer shape of a
Providers.
Unfortunately, without your help, it cannot track the shape of the "default"
global state -- the one manipulated by the setGlobal
and addReducer
helper
functions.
In order to tell TypeScript the shape of your global state when you are not using
a Provider, create a file at src/global.d.ts
with the following contents:
; declare module 'reactn/default'
In the above file, we extend the Reducers
and State
interfaces in the
'reactn/default'
file. While you will never use 'reactn/default'
in
your code, ReactN will use it to determine the shape of the default
global state.
The above example will add append
, increment
, and doNothing
to your
useDispatch
and this.dispatch
auto-completion and typing. The parameters
and return values will also be correctly typed. In addition, it will also
add count
and value
to your useGlobal
and this.global
auto-competion
with the appropriate types as well.
Developer tools
ReactN is compatible with the Redux DevTools extension.
- Install the Redux DevTools extension to your browser or environment.
- Install the
redux
package to your project vianpm
oryarn
. This is used to create a middleware Redux store for the Redux DevTools extension.- You do not have to import or use the
redux
package anywhere in your project. - You do not need to create a Redux store, reducer, or actions.
redux
is just a peer dependency. It will be managed automatically.
- You do not have to import or use the
- Follow the instructions on the ReactN DevTools README.
Examples
Class components
By importing React from reactn
instead of react
, you bake global state
directly into the React namespace. As a result, Component
and PureComponent
will have access to the global
and dispatch
member variables and
setGlobal
method.
; // <-- reactn; // Render all cards in the global state.PureComponent { // Hydrate the global state with the response from /api/cards. this; } { // For each card in the global state, render a Card component. // this.global returns the global state, // much the same way this.state returns the local state. return <div> thisglobalcards </div> ; }
Class components (with decorator)
By importing React and ReactN separately, the React namespace remains
unchanged. You can inject ReactN's global functionality into your vanilla React
component by using the @reactn
decorator imported from the reactn
package.
;; // <-- reactn; // Render all cards in the global state.@reactnPureComponent { // Hydrate the global state with the response from /api/cards. this; } { // For each card in the global state, render a Card component. // this.global returns the global state, // much the same way this.state returns the local state. return <div> thisglobalcards </div> ; }
Function components
Using React Hooks, you can harness
useGlobal
to access the global state.
; // <-- reactn; // Render all cards in the global state.const Cards = { // Use the hook to get all cards in the global state. // setCards is not used in this example. const cards setCards = ; // For each card in the global state, render a Card component. return <div> cards </div> ;}; ;
You may also use the useDispatch
hook analogously to the useReducer
hook by
providing a function to useDispatch
.
; // <-- reactn const incrementReducer = count: globalcount + actionamount; const decrementReducer = count: globalcount - actionamount; const MyComponent = { const increment = ; const decrement = ; return <div> <button onClick= >Add 1</button> <button onClick= >Add 3</button> <button onClick= >Subtract 5</button> </div> ;}; ;
By providing a second parameter to useDispatch
that is the key of the global
state, the return value of that reducer will set that property of the global
state. This allows you to write your reducers similar to React's useReducer
.
; // <-- reactn const incrementReducer = count + actionamount; const decrementReducer = count - actionamount; const MyComponent = { const increment = ; const decrement = ; return <div> <button onClick= >Add 1</button> <button onClick= >Add 3</button> <button onClick= >Subtract 5</button> </div> ;}; ;
Helper functions
addCallback
Use addCallback
to execute a function whenever the state changes. The return
value of the callback will update the global state, so be sure to only return
undefined
or null
if you do not want the global state to change. Be aware
that always returning a new state value will result in an infinite loop, as the
new global state will trigger the very same callback.
The only parameter is the callback function.
; // Every time the global state changes, this function will execute.; ;// The new value is 1!// The new value is 2!
The return value of addCallback
is a function that, when executed, removes
the callback.
; const removeAlert = ; // The callback causes an alert on global state change:; // 1; // 2 // No longer execute the callback.; // No alerts:;;
addReducer
Use addReducer
to add a reducer to your global state.
The first parameter is the name of your reducer. You will access your reducer
by this name. this.dispatch.reducerName
or useDispatch('reducerName')
.
The second parameter is the reducer function. The reducer function that you write has at least two parameters: first, the global state; second, a map of your reducers. The third and onward parameters are the arguments that you pass when dispatching. The reducer function that you use when dispatching does not contain the global state or map of reducers. Those are prefixed for you automatically.
; // Initialize the global state with the value 0.; // When the increment reducer is called, increment the global value by X.; { const increment = ; const value = ; return <> The value is' ' <button onClick= { // Increment from 0 to 1. // (the default value of the reducer is 1) if value === 0 ; // Increment from 1 to 5. else if value === 1 ; } value=value /> </> ;}
For a class component, the analogous method is
this.dispatch.increment(value)
.
The dispatch
parameter on a reducer allows you to write "sagas," or a single
reducer that dispatches other reducers.
// add(1); // subtract(2); // addSubtract(1, 2);
addReducers
addReducers
accepts an object where the keys are reducer names and the values
are reducers. addReducers
is just a convenient shorthand for calling
addReducer
multiple times.
getDispatch
Use getDispatch
to return an object of the global dispatch functions. You
only want to use this in helper libraries, and not in Components. Components
should use useDispatch
or this.dispatch
.
getDispatch
has no parameters.
; // Access this.dispatch.reducerName outside of a Component. { return reducerName; }
getGlobal
Use getGlobal
to return a current snapshot of the global state. You only want
to use this in helper libraries, and not in Components. Components should use
useGlobal
or this.global
to ensure that they re-render when the global
state changes. getGlobal
will not cause a Component reliant on the global
state to re-render, nor will it cause a library function to re-execute. It does
nothing more than return a current snapshot of the global state.
getGlobal
has no parameters.
; // Access this.global.value outside of a Component. { return value; }
removeCallback
Use removeCallback
to remove a callback that was added via addCallback
. The
callback must be the same function reference. This is equivalent to executing
the return value of addCallback
.
The only parameter is the callback function itself.
; { ;} ; // Alerts the global state value:; // 1; // 2 // Remove the alert callback:; // No alerts:;;
resetGlobal
Use resetGlobal
to reset the global state. This resets all state values,
including callbacks, property listeners, and reducers.
There are no parameters.
; // Set the value.; // Get the value.; // 1 // Reset the global state.; // Get the value.; // undefined
setGlobal
Use setGlobal
to initialize or update your global state. This is analogous to
calling this.setGlobal
in a class component or useGlobal()[1]
in a
function component.
The first parameter is merged into the global state in the same way a class
component's this.setGlobal
merges its first parameter into the local state.
The optional second parameter is a callback.
setGlobal
with a new global state:
; // Set loading to true.;
setGlobal
with a new global state and a callback:
; // Set loading to true.;
useDispatch
Requires React >= 16.8.0
The useDispatch
helper function is a React Hook analogous to the useReducer
hook built into React itself. useDispatch
will dispatch a global reducer that
has been added to ReactN via the addReducer
,
addReducers
, or withInit
helper functions or a
global reducer that you specify inline as a parameter.
useDispatch()
useDispatch()
with no parameters will return a map of all of your global
reducers.
; { const dispatch = ; dispatch; dispatch; return null;}
useDispatch(Function)
useDispatch(f)
allows you to define your global reducer inline. This method
is particularly useful if you prefer to import your reducers as needed or keep
your singleton reducers with the components that use them.
; { const count = ; const add = ; return <button onClick= >count</span>;}
useDispatch(Function, keyof State)
useDispatch(f, 'property')
allows you to define your global property reducer
inline. A property reducer changes only one property of the global state, which
can greatly simplify your reducer logic.
; { const count = ; const add = ; return <button onClick= >count</span>;}
useDispatch(keyof Reducers)
useDispatch('reducerName')
allows you to dispatch a global reducer.
; { const count = ; const add = ; return <button onClick= >count</span>;}
useGlobal
Requires React >= 16.8.0
useGlobal
is a React Hook analogous to the useState
Hook built into React
itself. useGlobal
returns the global state or parts thereof.
useGlobal()
useGlobal()
with no parameters will return the entire global state object and
a function for changing properties of the global state.
The setGlobal
function returned by useGlobal
is analogous to the
setGlobal
helper function and this.setGlobal
class method.
; { const global setGlobal = ; const generateNumber = {
useGlobal(keyof State)
useGlobal('property')
returns a specific global state property and a function
for updating that property.
; const getRandomNumber = Math; { const myNumber setMyNumber = ; return <button onClick= >myNumber</button> ;}
withGlobal
Use withGlobal
to return a higher-order component to convert global state
values into props. This is highly analogous to react-redux
's connect
function.
The first parameter is a function for getting global state values.
The second parameter is a function for setting global state values (similar to
dispatch
).
; // A button that displays the value and, when clicked, increments it. { return <> My value is <button onClick=propsincrementValue value=propsvalue /> </> ;} // Set the `value` prop equal to the global state's `value` property. value: globalvalue // Important Note: This is not the setGlobal helper function. // Set the `incrementValue` prop to a function that increments the global // state's `value` property. { // Important Note: This is not the setGlobal helper function. // This is the parameter referenced 4 lines up. ; } MyComponent;
withInit
In some cases (such as when using Next.js), you may be unable to run a setup
script prior to your ReactN components mounting. In order to instantiate your
global state and reducers prior to mounting, you may use the withInit
Higher
Order Component. This HOC will await the setting of your global state before
mounting the provided Lower Order Component (e.g. <App />
).
; const INITIAL_REDUCERS = count: count + 1 ; const INITIAL_STATE = count: 0; INITIAL_STATE INITIAL_REDUCERS { const addOne = ; const count = ; return <button onClick=addOne>Count: count</button>;};
Known issues
super(props)
is incompatible with TypeScript. #126- Components re-render once per changed subscribed property. #129
- Class components use
componentWillUpdate
without theUNSAFE_
prefix. #134 - Class components are incompatible with Providers in newer versions of React. #132
Terminology
ReactN strictly maintains accurate terminology for its data structures. The majority of ReactN's data structures are meant to be black box to simplify the user experience, only referenced by name in the package's code. They are outlined here for transparency and to ease community contributions.
Dispatcher
When you pass a reducer to ReactN via addReducer
,
addReducers
, useDispatch
, or
withInit
, ReactN returns a dispatcher.
A dispatcher is a function that wraps a reducer, passing the global state and global reducers as parameters tying its return value to the global state. Dispatchers and reducers have a 1-to-1 relationship and are tightly bound to each other.
In documentation, dispatchers are often referred to as reducers to decrease the cognitive overhead and conceptually strengthen their 1-to-1 relationship.
For example, an "add" reducer may be defined as follows:
{ return count: globalcount + n ;}
When you call this reducer, you only need to call add(1)
. This difference in
call signature is because you are calling the dispatcher.
A dispatcher, in pseudo-code, conceptually looks as follows:
{ const dispatchers set state = globalStateManager; const newGlobalState = ; return ;}
Global state manager
The global state manager is the core object that powers ReactN. It maintains the state, global dispatchers, and subscriptions.
Default global state manager
The default global state manager is the global state manager used by all of ReactN unless otherwise specified. To specify a different global state manager, you must use a Provider.
ReactN Components and Hooks will attempt to find a global state manager via the Context. If one does not exist via Context, it will fallback to the default global state manager.
Reducer
A reducer is a function that accepts the current global state, a map of all global reducers, and any number of additional parameters. A reducer returns a change to the global state. It does not need to return the entire new global state. It only needs to return key-value pairs of changed properties.
An example "add" reducer may be defined as follows:
{ return count: globalcount + n ;}
A reducer may be asynchronous (return a Promise) and asynchronously dispatch other reducers. You can use a reducer that dispatches other reducers to create a "saga" of state changes.
{ if globalcount < 0 await dispatch; await dispatch; if shouldMultiply await dispatch; } ; // shouldMultiply = true
Property reducer
A property reducer is a reducer that only changes one property. They only receive that property's value as a parameter instead of the entire global state object, and they do not receive the dispatch object as a parameter at all.
An example "add" property reducer may be defined as follows:
{ return count + n;}
You must specify the property when using a property reducer. Property reducers cannot be added to or remembered by the global state manager.
; { return count + n;} { const count = ; // Use the "add" property reducer on the "count" property. const dispatch = ; return <button onClick= >count</button>;}
Sponsor
If you are a fan of this project, you may become a sponsor via GitHub's Sponsors Program.
Support
For support, reach out to us on the Reactiflux Discord channel #reactn.