Simple, lightweight state management library for ReactJS with zero dependencies, weighing in at just under 900 bytes (gzip).
- IMPORTANT: Upgrading from v1 to v2 includes breaking changes; see API below for new interfaces.
Installation
yarn add treble-hook
or
npm install --save treble-hook
Quick Start
import trebleHook usePub useSub from 'treble-hook' // Welcome.jsx { const guestName = return <h3>Welcome to treble-hook guestName || ''!</h3> } // GuestEntry.jsx { const pubGuestName = return <div> <input ="text" = /> </div> } // App.jsx { trebleHook const GuestPublisher = trebleHook return <GuestPublisher> <GuestEntry /> <br /> <Welcome /> </GuestPublisher> }
Live Examples on Codesandbox
- Welcome (Quick Start example with Typescript + Material-UI)
- Classic ToDo App
- Code Cracker Game (coming soon)
API
trebleHook.addTopic()
Adds a new topic that can be published and subscribed to.
addTopictopicName: string, defaultValue: T, initWithSessionStorage = false: void
topicName
is the identifier for the topic and must be unique within the application.defaultValue
will be used as the initial state value for respective topic.initWithSessionStorage
determines whether to retrieve the topic's initial state from session storage. Iftrue
, then all subsequent published state changes will also be stored in sessions state for the app. This is helpful to ensure consistent state between any routes that require hard reloads.
Example:
trebleHook.addTopic'apples', 25trebleHook.addTopic'organges', 42trebleHook.addTopic'carrots', 100
trebleHook.getPublisher()
Returns a TrebleHookPublisher JSX element that manages publications for given topics. The Publisher JSX should be placed high in the component tree (ancestral to all components that interact with the respective publisher state).
getPublishertopics?: string: TrebleHookPublisher JSX.Element
topics
is the array of topic names contextual to this publisher that have been added using theaddTopic
method. If no topics are passed in then all topics will be included in the returned publisher.
Example:
return
usePubSub
A hook that subscribes a component to a topic with capability to publish. The hook returns a tuple that is similar to the tuple returned from useState
where the first element is the topic's current state value and the second element is the method to publish a new state value for the topic.
usePubSubtopic: string: PubSubTuple<T>
topic
is the unique topic name to subscribe to.
Example:
usePub
A hook returning a function that publishes to a topic.
IMPORTANT: Even though this hook only returns the publish function, it will still cause a re-render whenever a value for respective topic is published outside the scope of this component (i.e. when published from another component).
usePubtopic: string:void
Example:
useSub
A hook returning a function that subscribes to a topic.
useSubtopic: string: T
Example: