github | npm | tosijs | discord
Incredibly simple, powerful, and efficient state management for React…
useTosi leverages React hooks to
make managing application state incredibly simple. No more passing data down through
the virtual DOM hierarchy, and needing to reroute data or write reducers.
This is an old example that uses
xinjsandreact-xinjs.xinjshas since been renamedtosijs.
useTosi allows you to use xin to manage state in ReactJS apps.
- work with pure components everywhere (use
useTosithe way you'd useuseState) - cleanly separate logic from presentation
- avoid code and performance "tax" of passing complex state through DOM hierarchies
- cleanly integrate react and non-react code without writing and maintaining wrappers
Pass any object to xin, then access it exactly like you would via useState
except using useTosi('path.to.value'). E.g.
import { xinProxy, useTosi } from 'xinjs'
const clock = xinProxy({ clock: {
time: new Date().toLocaleTimeString()
} })
setInterval(() => {
clock.time = new Date.toLocaleTimeString()
}, 1000)
const Clock = () => {
const [time] = useTosi('clock.time')
return <div>{clock.time}</div>
}
Note that useTosi returns [value, setValue] just as useState does
(and if you wanted to write a more complex self-contained that
sets up and tears down setInterval then nothing is stopping you except
wanting to write less, simpler code that runs faster), but in
this case the state is being updated outside of React and it just works.
Here's the good old React "to do list" example rewritten with xin
and only pure components.
- Fewer lines of code,
- Clean separation between logic and presentation,
- Better behavior, and
- Cleaner screen redraws (thanks to pure components)
Better, faster, cheaper. You can have all three.
import { xinProxy, useTosi } from 'xin-react'
const { app } = xinProxy({ app: {
itemText: '',
todos: [],
addItem(event) {
event.preventDefault() // forms reload the page by default!
if(!app.itemText) return
app.todos.push({
id: crypto.randomUUID(),
text: app.itemText
})
app.itemText = ''
}
} })
const Editor = () => {
const [itemText, setItemText] = useTosi('app.itemText')
return <form onSubmit={app.addItem}>
<input value={itemText} onInput={event => setItemText(event.target.value)} />
<button disabled={!itemText} onClick={app.addItem}>Add Item</button>
</form>
}
const List = () => {
const [todos] = useTosi('app.todos')
return <ul>
{ todos.map(item => <li key={item.id}>{item.text}</li>) }
</ul>
}
export defaul TodoApp = () => <div className="TodoApp" role="main">
<h1>To Do</h1>
<List />
<Editor />
</div>
root.render(<TodoTapp />)