react-reactive-var
TypeScript icon, indicating that this package has built-in type declarations

1.0.5 • Public • Published

react-reactive-var

Reactive variables for react using hooks.

NPM JavaScript Style Guide

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>
  )
}

View the example

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.

Readme

Keywords

none

Package Sidebar

Install

npm i react-reactive-var

Weekly Downloads

85

Version

1.0.5

License

MIT

Unpacked Size

600 kB

Total Files

29

Last publish

Collaborators

  • jorbuedo