Get / set store from React component
useStore​
const { useStore } = cervello({ example: true })
Description​
React hook that allows you to have a reactive store which re-renders when a new value was set to the store or any of its properties.
If you have set a name for the store, the returned object property will be use{name}Store
Returned value​
Type | Default | Description |
---|---|---|
Object | initial store value | Returned store object . You can modify it and it will notify all the components |
To consider
If you want to modify a property of the store, you need to use it without destructuring, like this:
const { useStore } = cervello({ isActive: true })
const ExampleComponent = () => {
const store = useStore()
return (
<button onClick={() => store.isActive = false}>
Set Active to false
</button>
)
}
Example​
- JavaScript
- TypeScript
import { useStore } from './store-example'
const CounterLabel = () => {
/**
* You can destructure the store because it just reads
* the value without any changes to store
*/
const { count } = useStore()
return (<span>{ count }</span>)
}
import { useStore } from './store-example'
const CounterLabel = () => {
/**
* You can destructure the store because it just reads
* the value without any changes to store
*/
const { count } = useStore()
return (<span>{ count }</span>)
}