Giter Club home page Giter Club logo

state's Introduction



Bundle size

Install

npm i @bit-about/state

Features

  • 100% Idiomatic React
  • 100% Typescript with state types deduction
  • Efficient sub-states selectors
  • Get state from a hook...
  • ...or utilise static access
  • No centralized state provider
  • Tiny - only 1.4kB
  • Just works β„’

➑️ Check demo

Usage

import { useState } from 'react'
import { state } from '@bit-about/state'

// 1️⃣ Create a hook-based store
const [Provider, useStore] = state(() => {
  const [alice, setAlice] = useState('Alice')
  const [bob, setBob] = useState('Bob')
  
  return { alice, setAlice, bob, setBob }
})

// 2️⃣ Wrap tree with Provider
const App = () => (
  <Provider>
    <Child />
  </Provider>
)

and then

// 3️⃣ Use the selector hook in component
const Child = () => {
  const alice = useStore(state => state.alice)
  
  return <p>{alice}</p>
}

State selectors

Access fine-grained control to the specific part of your state to re-render only when necessary.

// πŸ‘ Re-render when anything changed
const { alice, bob } = useStore()

// πŸ’ͺ Re-render when alice changed
const alice = useStore(state => state.alice)

// 🀌 Re-render when alice or bob changed
const [alice, bob] = useStore(state => [state.alice, state.bob])

// or
const { alice, bob } = useStore( 
  state => ({ alice: state.alice, bob: state.bob }) 
)

NOTE: Values in objects and arrays created on the fly are shallow compared.

Static store

The third element of the state() result tuple is a store object. Store is a static helper which provides access to the state without a hook.

const [Provider, useStore, store] = state(/* ... */)

and then

// πŸ‘ Get whole state
const { alice } = store.get()

// πŸ’ͺ Get substate
const alice = store
  .select(state => state.alice)
  .get()

// 🀌 Subscribe to the store and listen for changes
const subscription = store
  .select(state => state.alice)
  .subscribe(alice => console.log(alice))
  
// remember to unsubscribe!
subscription.unsubscribe()

State props

The state hook allows you to pass any arguments into the context. It can be some initial state or you could even return it and pass it through to the components. All state prop changes will update the context and trigger component re-rendering only when necessary.

import { useState } from 'react'
import { getUserById } from '../utils'

const [UserProvider, useUser] = state(props => {
  const [user] = useState(() => getUserById(props.id))
  return user
})

const UserProfile = () => (
  <UserProvider id={2137}>
    {/* ... */}
  </UserProvider>
)

πŸ‘‰ Functions in state

Please remember that functions defined without React.useCallback create themselves from scratch every time - which results in incorrect comparisons and components think the state has changed so they re-render themselves.

import { useState, useCallback } from 'react'

const [Provider, useStore] = state(() => {
  const [counter, setCounter] = useState(0);
   
  // βœ–οΈ It will re-render components every time
  // const incrementCounter = () => setCounter(value => value + 1)

  const incrementCounter = useCallback(
    () => setCounter(value => value + 1),
    [setCounter]
  )

  return { counter, incrementCounter }
})

BitAboutState πŸ’› BitAboutEvent

Are you tired of sending logic to the related components?
Move your bussiness logic to the hook-based state using @bit-about/state + @bit-about/event.

Now you've got completely type-safe side-effects. Isn't that cool?

import { useState } from 'react'
import { state } from '@bit-about/state'
import { useEvent } from './auth-events' // @bit-about/event hook
import User from '../models/user'

const [UserProvider, useUser] = state(() => {
  const [user, setUser] = useState<User | null>(null)
    
  useEvent({
    userLogged: (user: User) => setUser(user),
    userLoggout: () => setUser(null)
  })
    
  return user
})

BitAboutState πŸ’› React Query

import { useQuery } from 'react-query'
import { fetchUser } from './user'

const useUserQuery = (id) => useQuery(['user', id], () => fetchUser(id))

const [UserProvider, useUser] = state(props => {
  const { data: user } = useUserQuery(props.id)
  return user
})

const UserProfile = () => (
  <UserProvider id={2137}>
    {/* ... */}
  </UserProvider>
)

// 🧠 Re-render ONLY when user avatar changed (no matter if isLoading changes)
const avatar = useUser(state => state.user.avatar)

Partners

wayfdigital.com

Credits

License

MIT Β© Maciej Olejnik πŸ‡΅πŸ‡±

Support me

Support me!

If you use my library and you like it...
it would be nice if you put the name BitAboutState in the work experience section of your resume.
Thanks πŸ™‡πŸ»!


πŸ‡ΊπŸ‡¦ Slava Ukraini

state's People

Contributors

dependabot[bot] avatar macoley avatar xkrsz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

xkrsz amit08255

state's Issues

ESM modules not being generated

In package.json, line 15, you are specifically limiting the building to Common JS. ("--format cjs"), even though you named the ESM module on line 9 (""module": "dist/index.modern.js",).

Please remove the "--format cjs" from the build command and publish esm modules in the future.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.