Context
createNoyaContext
For more complex tools, Noya provides a React context-based API that offers fine-grained control over state management. The createNoyaContext
function creates a set of hooks that can be used to access and modify your tool's state.
- Call
const { Provider, useValueState, ... } = createNoyaContext({ schema })
to create the context. - Wrap your components with a
<Provider>
component. - Access the state with the hooks provided by the context:
const value = useValue()
const value = useValue(path: string | string[])
const value = useValue<T>(selector: (state) => T)
const [value, setValue] = useValueState()
const [value, setValue] = useValueState(path: string | string[])
const setValue = useSetValue()
const setValue = useSetValue(path: string | string[])
useValueState
The useValueState
is similar to React's useState
, but it reads from the state provider. Additionally, you may specify a path to read/write a nested value.
This hook will only trigger a re-render if the value at the specified path changes.
useValue
There are several ways to read state using the useValue
hook:
- Directly access the entire state using
useValue()
- Access a specific value using
useValue(path)
, wherepath
is a string of dot or slash-separated keys or an array of keys. - Use a selector function with
useValue(selector)
, whereselector
is a function that takes the entire state and returns the value you want. This hook will only trigger a re-render if the selected value changes. When using a selector function, make sure to memoize it withuseCallback
to avoid unnecessary re-renders.
useSetValue
The useSetValue
hook provides ways to update the state. This will have better performance than using useValueState
because it doesn't require re-rendering the component, so use it when you only need to update the state without reading from it.
Path Syntax
When accessing nested state, you can use dot or slash notation or array syntax:
- Dot notation:
"document.metadata.title"
- Slash notation:
"document/metadata/title"
- Array syntax:
["todos", 0]
Asset Management
Noya provides hooks for managing assets (like images and files).
- Call
useAssets()
for the full list of assets - Call
useAsset(id)
to get an asset by id. - Call
const { createAsset, deleteAsset } = useAssetManager()
to create and delete assets.
Note that these functions are imported directly from the
@noya-app/noya-multiplayer-react
package, rather than returned from thecreateNoyaContext
API.
More details here.
Type Safety
The context API is fully typed based on your JSON schema, providing autocomplete and type checking for paths and values.
Best Practices
Context Creation
We recommend creating a separate file for your state schema and exporting the context provider and hooks. This makes it easier to reuse the context in different parts of your app.
Performance
- Use the most specific path possible when reading state to minimize re-renders
- Memoize selector functions with
useCallback