Skip to content

Latest commit

 

History

History
69 lines (60 loc) · 1.13 KB

state.md

File metadata and controls

69 lines (60 loc) · 1.13 KB

State management

With createModel():

assuming you created your model with createModel()

const MyModel = createModel(Model<{
	x: number
}>)

Using component wrapper:

const MyComponent = MyModel.withModel(({
	model,
}) => {
	const [x, setX] = model.useState('x')
})

Using static MyModel.useState:

const MyComponent = () => {
	const [x, setX] = MyModel.useState('x')
}

With React.createContext():

const MyModelContext = React.createContext(new MyModelClass(initialState))

Using model instance:

const modelInstance = useModelCtx(MyModelContext)

const [x, setX] = modelInstance.useState('x')

Using state from context:

const [x, setX] = useModelCtxState(MyModelContext, 'x')

Using internal methods to avoid unnessesary rerenders

Using model.reduce:

const onClick = useCallback((x) => {
	model.reduce((state) => {
		return {
			count: state.count + x
		}
	}, [])
})

Using model.setState:

const onClick = useCallback((x) => {
	model.setState({
		count: x
	})
})

Using model.setValue:

const onClick = useCallback((x) => {
	model.setValue('state', x)
})