Skip to content

State management solution that allows 'lifting the state' without parent rerender

Notifications You must be signed in to change notification settings

krowter/react-wireless

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

react-wireless

Lifting the state without parent rerender

usage preview

Quick disclaimer

Most of the time, rerenders are fine and you shouldn't be bothered to optimize components when there are no signs of lagging and you still have other Jira tickets :). I created this just for fun and as a proof-of-concept.

Background

A while ago I stumbled upon Jack Herrington's video on Blazing Fast React Context (I really recommend watching it) and learned you can share state using Context without the parent rerendering.

Yesterday someone asked me "Why do we need to provide the value props to a Context's provider?" and it got me wondered "That's right. We provided the value already in createContext().". After some digging, it turns out the value from createContext() is used if no Provider exists.

I also have been wanting to publish an npm package.

Installation

npm install react-wireless

Usage

The source (or store or atom) lives outside the component.

import { createSource } from 'react-wireless'

const useCount = createSource(0)

The returned value is a custom hook so I recommend prefixing with "use".

Use it inside your component as a regular useState (that is, it destructures into a state getter and setter).

function NavBar() {
    const [count, setCount] = useCount()
}

Now any components that subscribes to useCount will rerender on state changes.

Oh, the setter also receives a callback just like useState's. Below is a contrived example of a counter app to illustrate the idea

const useCount = createSource(0)

function IncrementButton() {
    const [_, setCount] = useCount()

    return <button onClick={() => setCount(c => c + 1)}>+1</button> 
}

function CountDisplay() {
    const [count] = useCount()

    return <span>{count}</span>
}

// this App will not rerender on count changes
function App() {
    return <>
        <CountDisplay />
        <IncrementButton />
    </>
}

About

State management solution that allows 'lifting the state' without parent rerender

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published