Can declare state inside components? #488
Unanswered
happy-little-one
asked this question in
Q&A
Replies: 2 comments 4 replies
-
It's technically possible to create a component state, for example: export defalut () => {
const store = useRef(proxy({count: 0})).current
const {count} = useSnapshot(store)
} However, it doesn't feel like a best practice, because a) we often don't need render optimization for local states and b) state branching doesn't work with external stores. So, we don't document this usage explicitly. If your requirements is mutable style updating, use-immer is a good option. |
Beta Was this translation helpful? Give feedback.
4 replies
-
Another alternative: import { useRef } from 'react'
import { proxy } from 'valtio'
import { useProxy } from 'valtio/utils'
function useValtio<T extends object>(data: T) {
const state = useRef(proxy<T>(data)).current
return useProxy(state)
} function App() {
const counter = useValtio({
count: 0,
get doubled() {
return this.count * 2
},
increment() {
counter.count++
},
})
return (
<button onClick={counter.increment}>Counter: {counter.count} * 2 = {counter.doubled}</button>
)
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
this is the regluar way to daclare the store:
well, in this way, the store is shared, every component instance use the same store. I want use valtio the manange the local store like useState. way don't just useState ? useState is hard to use, verbose, need immutable...If valtio has a way to manage local state, I think I will giveup react hooks at all ! if valtio has not yet, I think it is really worth achieving!
Beta Was this translation helpful? Give feedback.
All reactions