• 欢迎光临~

[React] Valtio proxy-state management lib intro

开发技术 开发技术 2022-12-21 次浏览

https://bestofjs.org/projects/valtio

Cool things about Valtio, it is completely independ from React component.

It is self testable and hook with React very well.

import {proxy, useSnapshot} from 'valtio'
import {saveInfo} from './api';

const state = proxy({
  count: 0,
  setCount: (count: number) => {
    state.count = count
  },
  inc: () => {
    state.count++
  },
  onClick: async () => {
    // an async operation here
    // such as api call and setTimeout
    // will not trigger react reredner the component
    // if using it inside react component, need to be careful
    await saveInfo();
    state.inc()
  }
})

export default function App() {
  const snap = useSnapshot(state)
  
  return (
    <>
      <h1>Count: {snap.count}</h1>
      <button onClick={snap.onClick}>+1</button>
    </>
  )
}

 

程序员灯塔
转载请注明原文链接:[React] Valtio proxy-state management lib intro
喜欢 (0)