useSiteState
Location: /src/hooks/use-site-state.js
The useSiteState
hook provides a generic, global settings context for the site. Many of its properties and methods returned by default are necessary for various pieces of corgi page management logic. However, it's an extremely open-ended hook, so in addition to these properties and methods, you are encouraged to add your own global/site-wide state if needed.
Any change of state within a Context Provider will cause a re-render of all of its children. Only use this hook if you're absolutely sure that the state needs to managed at the app-level.
useSiteState()
Return value
useSiteState
returns an object containing the following properties:
Property | Type | Description |
---|---|---|
modalOpen | Boolean | A flag for the full scope of your site, which tells all child components when a Modal window is open. Note that corgi does not provide a modal component out of the box. |
setModalOpen | Function | An updater function for the modalOpen state. It can be useful to call this function along with your modal open/close implementation, passing in whatever the "open" state is. |
background | String | A generic value that can be used to set an element's background from much deeper in the DOM. |
setBackground | Function | An updater function for the background state. |
pageHistory | Array | A reverse-chronological list of page directory names that have been visited, for use under the hood in the useLocale hook. |
addPage | Function | Adds the provided value to the beginning of the pageHistory array. |
version | String | The app version, as specified in package.json . |
Usage
The following is just an example of the many things you could do with this hook — it's really quite open-ended. Here we're setting a property on the site state context, called background
, from within a component <MyComponent>
. In the next code block, we're using that background
value to manipulate a CSS custom property on the <div id="main-content">
element.
import { useEffect } from "react"
import { useSiteState } from "@local/hooks";
const MyComponent = () => {
const { setBackground } = useSiteState();
useEffect(() => {
// sets the background property of the siteState to "red", on mount.
setBackground("red")
}, [])
...
};
import { useSiteState } from "@local/hooks";
const Page = ({ children, className, version }) => {
const { background } = useSiteState();
return (
<div
id="main-content"
className={styles.mainContent}
style={{ "--bg": background }}
>
{children}
</div>
);
};
export default Page;
The CSS module for the <Page>
component above might then look something like:
.mainContent {
background: var(--bg);
}