- Published on
- 🍵 2 min read
What Is Valtio? How to Set Up for a React Project?
- Authors
- Name
- Emin Vergil
- @eminvergil
Overview
Valtio is a global state management library for React. Valtio is similar to other state management libraries such as Redux or Context API where you have a global context but it is much simpler to setup.
How to setup Valtio for React Project ?
Take the following steps to setup valtio in your react application:
1 - install valtio
yarn add valtio
2 - create a global context file/folder
You can keep your folder structure like the example given below.
- App
- src
- components
- style
- hooks
- pages
- context
- globalContext.js
- ...
3 - create a proxy for your state
import { proxy } from 'valtio'
const state = proxy({ count: 0, text: 'hello' })
The proxy tracks changes to the original object and all nested objects, notifying listeners when an object is modified.src
4 - Read or mutate the state
You can read a valtio state using useSnapshot
hook.
Rule of thumb: read from snapshots, mutate the source.
If you want to mutate a state you can access directly to the state and change it.
Example:
// create a global state and assign an object for initial value.
export const state = proxy({
count: 10,
})
//change the state by directly accessing it
import state from '../globalContext.js'
state.count = 25