react-reactive-var
v1.0.5
Published
Reactive variables for react using hooks.
Downloads
494
Readme
react-reactive-var
Reactive variables for react using hooks.
Table of Contents
Install
npm install --save react-reactive-var
Usage
// vars.ts
import { makeVar } from 'react-reactive-var'
export const counterVar = makeVar<number>(0)
// button.tsx
import React from 'react'
import { counterVar } from './vars'
export default () => {
const handleClick = () => counterVar(counterVar() + 1)
return <button onClick={handleClick}>Click!</button>
}
// example.tsx
import React from 'react'
import { useReactiveVar } from 'react-reactive-var'
import Button from './Button'
import { counterVar } from './vars'
export default () => {
const example = useReactiveVar(counterVar)
return (
<div>
<div>{example}</div>
<Button />
</div>
)
}
API
makeVar
Creates a new reactive variable, which is a tiny evented variable.
Parameters
initialValue
First parameter sets the initial value of the variable.equalsFunc
Optional equals function to compare current value with a new one. Without it a strict equality operation is used.
Returns a ReactiveVar
useReactiveVar
A react hook that subscribes to changes in a ReactiveVar
to rerender the component when the variable changes. Must follow the Rules of Hooks.
Parameters
ReactiveVar
type ReactiveVar
- It's a function. Call it without parameters to get the value. Call it with a parameter to set the value. Also accepts a function to update the value from the current one.
.subscribe
Attribute function. Call it with a handler to be called whenever the variable is updated. Returns an unsuscribe function..unsuscribe
Attribute function. Call it with the same handler as the subscribe function to unsuscribe.
License
MIT © jorbuedo
This hook is created using create-react-hook.