Overview
The useStore
hook is used for managing global store state.
The main difference between React's useState
and Shogun Frontend's useStore
hook is that passing an object to the setter function will merge those changes with the previous store values.
Import
@getshogun/frontend-hooks
is already pre-installed on every Shogun Frontend store. It contains useStore
and other hooks. To import:
import useStore from 'frontend-store'
Usage
Below is an example on how to set a global state using useStore
:
import React from 'react'
import useStore from 'frontend-store'
const MyComponent = () => {
const [store, setStore] = useStore()
console.log(store) // initial state is `{}`
return (
<div>
<button onClick={() => setStore({ foo: 'bar' })}>
Update store
</button>
<div>
)
}
export default MyComponent
To access the global state in a different Component/Section:
import React from 'react'
import useStore from 'frontend-store'
const AnotherComponent = () => {
const [store] = useStore()
console.log(store) // state is `{ foo: 'bar' }`
return (
<p>
The global state for 'foo' is: {store.foo}
<p>
)
}
export default AnotherComponent