### Example: Get All Mounted Atoms and Their Values
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/store-composition.md
Illustrates how to compose a store with dev tools and then iterate through all mounted atoms to log their debug labels and current values or errors.
```typescript
import { composeWithDevTools } from 'jotai-devtools/utils/internals/compose-with-devtools';
import { createStore } from 'jotai';
const store = createStore();
const devStore = composeWithDevTools(store);
const atoms = devStore.getMountedAtoms();
atoms.forEach(atom => {
const state = devStore.getAtomState(atom);
console.log(
atom.debugLabel,
'value' in state ? state.v : state?.e
);
});
```
--------------------------------
### Minimal DevTools Setup
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/configuration.md
Basic setup for Jotai DevTools with default configurations.
```typescript
```
--------------------------------
### Install Jotai DevTools
Source: https://github.com/jotaijs/jotai-devtools/blob/main/README.md
Install the jotai-devtools package using yarn or npm.
```sh
# yarn
yarn add jotai-devtools
# npm
npm install jotai-devtools --save
```
--------------------------------
### Provider-less DevTools Setup
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/devtools-component.md
Basic setup for the DevTools component without a custom Jotai store, suitable for simple applications.
```typescript
import { DevTools } from 'jotai-devtools';
import 'jotai-devtools/styles.css';
export function App() {
return (
<>
{/* Your app components */}
>
);
}
```
--------------------------------
### AtomsSnapshot Example
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/types.md
Example of creating an AtomsSnapshot object with sample atom values and dependencies.
```typescript
const snapshot: AtomsSnapshot = {
values: new Map([
[countAtom, 42],
[nameAtom, 'Alice'],
]),
dependents: new Map([
[countAtom, new Set([derivedAtom])],
[nameAtom, new Set()],
]),
};
```
--------------------------------
### Setup GitHub Token
Source: https://github.com/jotaijs/jotai-devtools/blob/main/docs/internal/release-guide.md
Set up your GitHub token locally and verify its presence. This token is required for interacting with GitHub during the release process.
```bash
echo $GITHUB_TOKEN
```
--------------------------------
### Example Usage of useStore Options
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/types.md
Demonstrates how to use the store selection options with useAtomsSnapshot and useGotoAtomsSnapshot hooks, passing a custom store instance.
```typescript
useAtomsSnapshot({ store: customStore });
useGotoAtomsSnapshot({ store: customStore });
```
--------------------------------
### Basic Setup: All Atoms in Redux DevTools
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/useatomsdevtools.md
This snippet demonstrates the basic setup for tracking all Jotai atoms in Redux DevTools. It requires importing the hook and then calling it with a unique store name.
```typescript
import { useAtomsDevtools } from 'jotai-devtools';
import { atom, useAtom } from 'jotai';
const countAtom = atom(0);
const nameAtom = atom('Alice');
export function App() {
// Track all atoms in Redux DevTools
useAtomsDevtools('JotaiStore');
return (
);
}
function UserInfo() {
const [name, setName] = useAtom(nameAtom);
return (
setName(e.target.value)}
/>
);
}
```
--------------------------------
### Example: Using isDevToolsStore and composeWithDevTools
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/store-composition.md
Demonstrates how to compose a store with dev tools and then use the `isDevToolsStore` type guard to safely access developer methods.
```typescript
import { useStore } from 'jotai/react';
import { isDevToolsStore, composeWithDevTools } from 'jotai-devtools/utils/internals/compose-with-devtools';
const store = useStore();
const composedStore = composeWithDevTools(store);
if (isDevToolsStore(composedStore)) {
const atoms = composedStore.getMountedAtoms();
console.log('Mounted atoms:', atoms);
}
```
--------------------------------
### Undo/Redo Implementation Snippet
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/OVERVIEW.md
A concise example demonstrating the usage of `useAtomsSnapshot` and `useGotoAtomsSnapshot` for implementing undo/redo functionality.
```typescript
const snapshot = useAtomsSnapshot();
const restore = useGotoAtomsSnapshot();
// Save and restore as needed
```
--------------------------------
### Babel Plugin Setup for Jotai DevTools
Source: https://github.com/jotaijs/jotai-devtools/blob/main/README.md
Configure Babel plugins for enhanced debugging and hot reloading with Jotai atoms. This setup is optional but recommended for an optimal debugging experience.
```ts
{
"plugins": [
// Enables hot reload for atoms
"jotai/babel/plugin-react-refresh",
// Automatically adds debug labels to the atoms
"jotai/babel/plugin-debug-label"
]
}
```
--------------------------------
### DevTools Configuration Options
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/devtools-component.md
Example of configuring DevTools with various options like initial open state, theme, position, and behavior settings.
```typescript
import { DevTools } from 'jotai-devtools';
import 'jotai-devtools/styles.css';
export function App() {
return (
<>
{/* Your app components */}
>
);
}
```
--------------------------------
### Run Release Script
Source: https://github.com/jotaijs/jotai-devtools/blob/main/docs/internal/release-guide.md
Execute the release script to install dependencies, bundle files, and initiate the release process. This command automates several steps of the release.
```bash
pnpm run release
```
--------------------------------
### Connecting to a Custom Jotai Store
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/useatomsdevtools.md
This example shows how to connect `useAtomsDevtools` to a specific Jotai store instance created with `createStore`, rather than the default one.
```typescript
import { createStore } from 'jotai';
import { useAtomsDevtools } from 'jotai-devtools';
const customStore = createStore();
export function App() {
useAtomsDevtools('CustomStore', {
store: customStore,
});
return
App content
;
}
```
--------------------------------
### Provider-less Jotai DevTools Setup
Source: https://github.com/jotaijs/jotai-devtools/blob/main/README.md
Integrate Jotai DevTools into your application without a Jotai Provider. Ensure to import the necessary CSS.
```tsx
import { DevTools } from './JotaiDevTools';
import 'jotai-devtools/styles.css';
const App = () => {
return (
<>
{/* your app */}
>
);
};
```
--------------------------------
### Production-Ready DevTools Setup
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/configuration.md
Configure Jotai DevTools for production with specific positioning, theme, and options like snapshot history limit.
```typescript
```
--------------------------------
### DevTools Setup with Custom Store
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/devtools-component.md
Integrates the DevTools component with a custom Jotai store instance, allowing for more controlled state management.
```typescript
import { createStore } from 'jotai';
import { Provider } from 'jotai/react';
import { DevTools } from 'jotai-devtools';
import 'jotai-devtools/styles.css';
const customStore = createStore();
export function App() {
return (
{/* Your app components */}
);
}
```
--------------------------------
### Provider-based Jotai DevTools Setup
Source: https://github.com/jotaijs/jotai-devtools/blob/main/README.md
Set up Jotai DevTools with a custom store using Jotai's Provider. Import the DevTools component and its CSS.
```tsx
import { createStore } from 'jotai';
import { DevTools } from 'jotai-devtools';
import 'jotai-devtools/styles.css';
const customStore = createStore();
const App = () => {
return (
{/* your app */}
);
};
```
--------------------------------
### Configure DevTools Behavior Options
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/configuration.md
Passed via the 'options' prop to configure DevTools behavior. This example sets multiple behavior options.
```typescript
```
--------------------------------
### Development Debugging Setup
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/configuration.md
Configure Jotai DevTools for development debugging with initial open state and expanded JSON tree view.
```typescript
```
--------------------------------
### Basic Setup: Automatic in Development
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/useatomsdebuvalue.md
Use this snippet for automatic debugging in development environments. No explicit configuration is needed as it's enabled by default when `__DEV__` is true.
```typescript
import { useAtomsDebugValue } from 'jotai-devtools';
export function MyComponent() {
// Automatically enabled in development (__DEV__ = true)
useAtomsDebugValue();
return
Component content
;
}
```
--------------------------------
### Example: Subscribe to Store Changes
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/store-composition.md
Shows how to subscribe to store changes using `subscribeStore` and handle different event types like 'set', 'sub', 'unsub', 'async-get', and 'restore'.
```typescript
import { composeWithDevTools } from 'jotai-devtools/utils/internals/compose-with-devtools';
const devStore = composeWithDevTools(store);
const unsubscribe = devStore.subscribeStore((event) => {
switch (event.type) {
case 'set':
console.log('Atom value changed');
break;
case 'sub':
console.log('Component subscribed to atom');
break;
case 'unsub':
console.log('Component unsubscribed from atom');
break;
case 'async-get':
console.log('Async atom value completed');
break;
case 'restore':
console.log('Atoms restored from snapshot');
break;
}
});
```
--------------------------------
### Basic Jotai DevTools Integration
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/QUICK_REFERENCE.md
A simple example of how to include the DevTools component in your application. Ensure the CSS is imported for proper styling.
```typescript
function App() {
return (
<>
{/* Your app */}
>
);
}
```
--------------------------------
### Show Dependencies Between Atoms
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/useatomssnapshot.md
This example shows how to visualize the dependency graph between atoms using the `dependents` map returned by useAtomsSnapshot. This helps in understanding how atoms relate to each other.
```typescript
import { useAtomsSnapshot } from 'jotai-devtools';
import { atom } from 'jotai';
const baseAtom = atom(10);
const derivedAtom = atom((get) => get(baseAtom) * 2);
export function DependencyViewer() {
const snapshot = useAtomsSnapshot();
return (
);
}
```
--------------------------------
### Use a Custom Store with useAtomsSnapshot
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/useatomssnapshot.md
This example shows how to provide a custom Jotai store to useAtomsSnapshot using the `store` option. This is useful when you have multiple independent stores in your application.
```typescript
import { createStore } from 'jotai';
import { useAtomsSnapshot } from 'jotai-devtools';
const customStore = createStore();
export function CustomStoreDebugger() {
const snapshot = useAtomsSnapshot({
store: customStore,
});
return
{JSON.stringify(snapshot.values.size, null, 2)}
;
}
```
--------------------------------
### Debug Output Format Example
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/useatomsdebuvalue.md
Illustrates the expected format of the debug output within React DevTools, showing atom values, errors, and dependents.
```typescript
{
countAtom: {
value: 42,
dependents: ['derivedAtom', 'selectorAtom']
},
nameAtom: {
value: "Alice",
dependents: []
},
asyncAtom: {
error: Error: Failed to fetch,
dependents: ['displayAtom']
}
}
```
--------------------------------
### useGotoAtomsSnapshot
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/usegotoatomssnapshot.md
Hook to get a callback function for restoring atom snapshots. It accepts an optional options object to specify the store.
```APIDOC
## Function: useGotoAtomsSnapshot
### Signature
```typescript
export function useGotoAtomsSnapshot(options?: Options): (snapshot: AtomsSnapshot) => void;
```
### Parameters
#### Options
- **options** (Options) - Optional - Description: Store selection options (same as `useStore` from `jotai/react`).
### Returns
A callback function with the signature `(snapshot: AtomsSnapshot) => void`. This function accepts an `AtomsSnapshot` and applies its values to the current store.
```
--------------------------------
### Redux Extension Integration
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/README.md
Guide on integrating Jotai DevTools with the Redux DevTools extension, covering connection functions, message handling, and supported features.
```APIDOC
## Redux Extension Integration
### Description
Provides a guide for integrating Jotai DevTools with the Redux DevTools browser extension, enabling seamless debugging of Jotai state using familiar Redux DevTools workflows.
### `getReduxExtension` Function
Details the function to retrieve the Redux DevTools extension instance.
### `createReduxConnection` Function
Documentation for the function used to establish a connection between Jotai and Redux DevTools.
### Connection Methods (`init`, `subscribe`, `send`)
Reference for the core methods used for communication with the Redux DevTools extension.
### Message Types and Formats
Explains the structure and types of messages exchanged between Jotai and Redux DevTools.
### Features Support Matrix
A table outlining which Redux DevTools features are supported.
### Error Handling Guide
Best practices and strategies for handling errors during Redux DevTools integration.
```
--------------------------------
### React DevTools Integration Snippet
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/OVERVIEW.md
A minimal example showing how to integrate Jotai atoms with React DevTools using the `useAtomsDebugValue` hook.
```typescript
useAtomsDebugValue();
```
--------------------------------
### Basic Time-Travel: Save and Restore State
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/usegotoatomssnapshot.md
Demonstrates saving the current atom snapshot and restoring it later using useGotoAtomsSnapshot. This is a fundamental example for implementing time-travel debugging.
```typescript
import { useAtomsSnapshot, useGotoAtomsSnapshot } from 'jotai-devtools';
import { atom, useAtom } from 'jotai';
const countAtom = atom(0);
export function TimeTravel() {
const snapshot = useAtomsSnapshot();
const goToSnapshot = useGotoAtomsSnapshot();
const [count, setCount] = useAtom(countAtom);
const savedSnapshots = useRef([]);
return (
Count: {count}
);
}
```
--------------------------------
### Compose Store with DevTools
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/QUICK_REFERENCE.md
Enhances a Jotai store with developer methods, such as getting mounted atoms, their states, and subscribing to store events. Useful for advanced debugging and store inspection.
```typescript
import { composeWithDevTools } from 'jotai-devtools/utils/internals/compose-with-devtools';
const devStore = composeWithDevTools(store);
devStore.getMountedAtoms();
devStore.getAtomState(atom);
devStore.getMountedAtomState(atom);
devStore.restoreAtoms(values);
devStore.subscribeStore((event) => {});
```
--------------------------------
### Get Mount Information for an Atom
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/store-composition.md
Retrieves mount information for an atom, including its listeners and dependent atoms. Returns undefined if the atom is not currently mounted.
```typescript
getMountedAtomState(atom: Atom):
| {
readonly l: Set<() => void>; // listeners
readonly t: Set>; // dependents (atoms that depend on this)
}
| undefined;
```
--------------------------------
### DISPATCH Message with PAUSE_RECORDING
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/redux-extension.md
Example of a DISPATCH message to toggle the recording of actions in Redux DevTools.
```typescript
{
type: 'DISPATCH',
payload: {
type: 'PAUSE_RECORDING'
}
}
```
--------------------------------
### DISPATCH Message with IMPORT_STATE
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/redux-extension.md
Example of a DISPATCH message to import multiple state snapshots into Redux DevTools.
```typescript
{
type: 'DISPATCH',
payload: {
type: 'IMPORT_STATE',
nextLiftedState: {
computedStates: [
{ state: {count: 0} },
{ state: {count: 1} },
{ state: {count: 5} }
]
}
}
}
```
--------------------------------
### DISPATCH Message with JUMP_TO_ACTION
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/redux-extension.md
Example of a DISPATCH message used to jump to a specific action in the Redux DevTools history.
```typescript
{
type: 'DISPATCH',
payload: {
type: 'JUMP_TO_ACTION',
actionId: 5
},
state: '{"count":50,"name":"Alice"}'
}
```
--------------------------------
### Error Handling: Redux Extension Not Available
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/redux-extension.md
Checks if the Redux DevTools extension is available and provides a fallback mechanism if it's not installed.
```typescript
const extension = getReduxExtension();
if (!extension) {
console.warn('Redux DevTools not installed');
// Use fallback debugging method
}
```
--------------------------------
### Login to npm
Source: https://github.com/jotaijs/jotai-devtools/blob/main/docs/internal/release-guide.md
Log in to your npm account before proceeding with the release. This is a prerequisite for publishing packages.
```bash
npm login
```
--------------------------------
### Get All Currently Mounted Atoms
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/store-composition.md
Retrieves an iterable of all atoms that are currently subscribed to by at least one component. Useful for inspecting active atoms.
```typescript
getMountedAtoms(): Iterable>;
```
--------------------------------
### Manual State Management with Snapshot and Restore
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/INDEX.md
Use `useAtomsSnapshot` to capture the current state and `useGotoAtomsSnapshot` to restore it. This is useful for implementing undo/redo functionality.
```typescript
import { useAtomsSnapshot, useGotoAtomsSnapshot } from 'jotai-devtools';
function MyComponent() {
const snapshot = useAtomsSnapshot();
const restore = useGotoAtomsSnapshot();
const handleUndo = () => {
// Save previous snapshot before restoring
restore(previousSnapshot);
};
}
```
--------------------------------
### Import Jotai DevTools CSS
Source: https://github.com/jotaijs/jotai-devtools/blob/main/README.md
Shows how to import Jotai DevTools' styles using native CSS. This replaces the previous dependency on @emotion/react.
```diff
import { DevTools } from 'jotai-devtools';
+ import 'jotai-devtools/styles.css';
```
--------------------------------
### composeWithDevTools
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/store-composition.md
Wraps a Jotai store with developer methods for debugging and introspection. If the store is already composed, it returns the original store.
```APIDOC
## Function: composeWithDevTools
Wraps a Jotai store with developer methods for debugging and introspection.
### Signature
```typescript
export const composeWithDevTools = (
store: Store,
): typeof store | WithDevToolsStore;
```
### Parameters
- **store** (`Store`) - Required - A Jotai store instance from `createStore()`
### Return Type
Returns the same store with developer methods added, or the original store if it was already composed.
```typescript
type WithDevToolsStore = S & DevToolsStoreMethods;
type DevToolsStoreMethods = {
subscribeStore: (l: DevSubscribeStoreListener) => () => void;
getMountedAtoms: () => Iterable>;
getAtomState: (atom) => AtomState | undefined;
getMountedAtomState: (atom) => MountedAtomState | undefined;
restoreAtoms: (values: Iterable) => void;
};
```
### Methods
#### subscribeStore
Subscribe to store change events.
```typescript
subscribeStore(
listener: (event: {type: 'set' | 'sub' | 'unsub' | 'async-get' | 'restore'})
) => () => void;
```
Called when atoms are set, subscribed, unsubscribed, async values complete, or restored. Returns an unsubscribe function.
#### getMountedAtoms
Get all currently mounted atoms.
```typescript
getMountedAtoms(): Iterable>;
```
Returns atoms that are currently subscribed by at least one component.
#### getAtomState
Get the internal state of an atom.
```typescript
getAtomState(atom: Atom):
| {readonly v: unknown; readonly d: Iterable} // value state
| {readonly e: unknown; readonly d: Iterable} // error state
| undefined;
```
Returns an object with `v` (value) and `d` (dependencies) if the atom has a value, an object with `e` (error) and `d` (dependencies) if the atom has an error, or `undefined` if the atom is not in state.
#### getMountedAtomState
Get mount information for an atom.
```typescript
getMountedAtomState(atom: Atom):
| {
readonly l: Set<() => void>; // listeners
readonly t: Set>; // dependents (atoms that depend on this)
}
| undefined;
```
Returns an object with `l` (listeners) and `t` (dependent atoms) if the atom is mounted, or `undefined` if the atom is not mounted.
#### restoreAtoms
Restore atoms to specific values.
```typescript
restoreAtoms(values: Iterable, unknown]>): void;
```
Sets atoms to the provided values. Only writable atoms with initial values are updated.
```
--------------------------------
### Manual State Management with Undo/Redo
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/OVERVIEW.md
Implement manual state management, including undo/redo functionality, using `useAtomsSnapshot` and `useGotoAtomsSnapshot` hooks.
```typescript
import { useAtomsSnapshot, useGotoAtomsSnapshot } from 'jotai-devtools';
function UndoRedo() {
const snapshot = useAtomsSnapshot();
const restore = useGotoAtomsSnapshot();
const [history, setHistory] = useState([]);
const undo = () => {
const prev = history.pop();
if (prev) restore(prev);
};
}
```
--------------------------------
### Get Redux DevTools Extension
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/QUICK_REFERENCE.md
Retrieves the Redux DevTools extension if available. This utility function can be used to check for the extension's presence and enable/disable it.
```typescript
import { getReduxExtension } from 'jotai-devtools/utils';
const extension = getReduxExtension(enabled?: boolean);
// Returns: ReduxExtension | undefined
```
--------------------------------
### Use localStorage for Theme Persistence
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/INTERNALS.md
Initializes a color scheme manager that uses the browser's localStorage to store the user's theme preference.
```typescript
const colorSchemeManager = localStorageColorSchemeManager({
key: 'jotai-devtools-color-scheme',
});
```
--------------------------------
### createReduxConnection
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/redux-extension.md
Establishes a connection to the Redux DevTools extension for a given atom or store. It requires the extension instance obtained from `getReduxExtension` and a name for the connection, which will be displayed in the Redux DevTools UI. Returns a connection object with methods for initialization, subscription, and state updates, or `undefined` if the extension is not available.
```APIDOC
## Function: createReduxConnection
Creates a connection to Redux DevTools for an atom or store.
### Signature
```typescript
export const createReduxConnection = (
extension: ReduxExtension | undefined,
name: string,
): Connection | undefined;
```
### Parameters
#### Path Parameters
- **extension** (ReduxExtension | undefined) - Required - The extension from `getReduxExtension()`
- **name** (string) - Required - Name for the connection (displayed in Redux DevTools)
### Return Type
```typescript
export type Connection = {
shouldInit?: boolean;
init: ConnectResponse['init'];
subscribe: (listener: (message: Message) => void) => (() => void) | undefined;
send: ConnectResponse['send'];
};
```
Returns a connection object or `undefined` if extension is not available.
### Connection Methods
#### shouldInit
Flag indicating the connection needs initialization.
```typescript
let shouldInit = true; // Set automatically
// Later, after calling init()
shouldInit = false;
```
#### init(state)
Initialize the connection with initial state.
```typescript
connection.init(initialState);
```
Called once to set the baseline state in Redux DevTools history.
Parameters:
- `state`: Initial state value (should be JSON-serializable)
#### subscribe(listener)
Subscribe to Redux DevTools messages.
```typescript
const unsubscribe = connection.subscribe((message) => {
if (message.type === 'DISPATCH') {
if (message.payload?.type === 'JUMP_TO_STATE') {
// User time-traveled in Redux DevTools
const newState = JSON.parse(message.state);
applyNewState(newState);
}
}
});
```
Listener receives `Message` objects with:
- `type`: Message type ('DISPATCH', 'ACTION', etc.)
- `payload`: Action metadata (contains `type` like 'JUMP_TO_ACTION', 'PAUSE_RECORDING')
- `state`: JSON state string for time-travel operations
Returns an unsubscribe function, or `undefined` if subscription failed.
#### send(action, state)
Send a state change to Redux DevTools.
```typescript
connection.send('INCREMENT', { count: 1 });
connection.send({ type: 'User Updated', timestamp: Date.now() }, { name: 'Alice' });
```
Parameters:
- `action`: Action label (string or object) describing the change
- `state`: New state value (must be JSON-serializable)
Called each time the atom/store value changes.
## Redux DevTools Message Types
Messages received by the `subscribe` listener:
### ACTION Message
User dispatched an action from Redux DevTools console.
```typescript
{
type: 'ACTION',
payload: JSON.stringify({/* user input */})
}
```
```
--------------------------------
### Store Composition
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/README.md
Documentation on developer store methods and functions for advanced store manipulation, including composing stores with developer tools and accessing internal store functionalities.
```APIDOC
## Store Composition
### Description
Details advanced methods for composing and interacting with Jotai stores, particularly when integrating with developer tools.
### `composeWithDevTools` Function
Documentation for the function used to enhance a store with developer tool capabilities.
### `isDevToolsStore` Type Guard
Information on the type guard for identifying developer-tool-enabled stores.
### All Developer Methods Documented
Comprehensive reference for all available developer methods on the store.
### Examples
- Getting atom values programmatically.
- Subscribing to atom changes.
- Implementing time-travel logic.
- Analyzing atom dependencies.
### Implementation Details and Performance
Insights into the internal implementation and performance characteristics of store composition.
```
--------------------------------
### DISPATCH Message with JUMP_TO_STATE
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/redux-extension.md
Example of a DISPATCH message used to jump to a specific state, often used when comparing states in the Redux DevTools diff view.
```typescript
{
type: 'DISPATCH',
payload: {
type: 'JUMP_TO_STATE'
},
state: '{"count":42,"name":"Bob"}'
}
```
--------------------------------
### Store Composition Layer
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/INTERNALS.md
Illustrates the flow for capturing atom values within the jotai-devtools store composition. It shows how `useAtomsSnapshot` utilizes `useDevToolsStore` which calls `composeWithDevTools` to return a store with developer methods.
```text
useAtomsSnapshot()
↓ uses ↓
useDevToolsStore()
↓ calls ↓
composeWithDevTools()
↓ returns ↓
WithDevToolsStore (store with developer methods)
↓ calls ↓
getMountedAtoms() → Iterable
↓ for each atom ↓
getAtomState(atom) → { v: value } | { e: error }
↓ returns ↓
AtomsSnapshot { values: Map, dependents: Map }
```
--------------------------------
### Check if Redux DevTools is Available
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/redux-extension.md
Use `getReduxExtension` to determine if the Redux DevTools extension is installed and accessible. This is useful for conditionally enabling Redux DevTools integration in your application.
```typescript
import { getReduxExtension } from 'jotai-devtools/utils';
const extension = getReduxExtension();
if (extension) {
console.log('Redux DevTools is available');
} else {
console.log('Redux DevTools is not available');
}
```
--------------------------------
### Restore State with Custom Store
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/usegotoatomssnapshot.md
Demonstrates using useGotoAtomsSnapshot with a custom Jotai store. This allows restoring state in a specific store instance rather than the default one.
```typescript
import { createStore } from 'jotai';
import { useGotoAtomsSnapshot } from 'jotai-devtools';
const customStore = createStore();
export function CustomStoreRestore() {
const goToSnapshot = useGotoAtomsSnapshot({
store: customStore,
});
const handleRestore = (savedSnapshot: AtomsSnapshot) => {
goToSnapshot(savedSnapshot);
};
return (
);
}
```
--------------------------------
### Store-Wide Debugging with Redux DevTools
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/redux-extension.md
Sets up a connection for the entire Jotai store to Redux DevTools. Initializes the connection and provides a function to send state updates.
```typescript
import { getReduxExtension, createReduxConnection } from 'jotai-devtools/utils';
import { useEffect, useRef } from 'react';
export function App() {
const connection = useRef(null);
useEffect(() => {
const extension = getReduxExtension();
if (!extension) return;
connection.current = createReduxConnection(extension, 'AppStore');
if (!connection.current) return;
connection.current.init({/* initial state */});
return () => {
connection.current = null;
};
}, []);
// Send updates to Redux DevTools whenever state changes
const sendStateUpdate = (state) => {
if (connection.current) {
connection.current.send('State Updated', state);
}
};
return
{/* Your app */}
;
}
```
--------------------------------
### Internal DevTools Context Provider
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/INTERNALS.md
Demonstrates how the `InternalDevToolsContext` provides the internal store, which is then used by the `useDevtoolsJotaiStoreOptions` wrapper to ensure DevTools UI atoms utilize the internal store.
```typescript
InternalDevToolsContext provides the internal store
↓ used by ↓
useDevtoolsJotaiStoreOptions() wrapper
↓ which returns ↓
{ store: internalStore }
↓ passed to ↓
useAtomValue/useSetAtom(..., options)
This ensures DevTools UI atoms use the internal store, not the user's store.
```
--------------------------------
### Get Internal State of an Atom
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/store-composition.md
Retrieves the internal state of a specific atom, including its value or error, and its dependencies. Returns undefined if the atom is not in the store's state.
```typescript
getAtomState(atom: Atom):
| {readonly v: unknown; readonly d: Iterable} // value state
| {readonly e: unknown; readonly d: Iterable} // error state
| undefined;
```
--------------------------------
### Match Store Configuration
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/configuration.md
Ensure the DevTools store configuration matches your application's store configuration for proper integration.
```typescript
const customStore = createStore();
{/* App */}
```
--------------------------------
### Force Disable Redux DevTools
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/redux-extension.md
Manually disable Redux DevTools integration by passing `false` to `getReduxExtension`. This will result in `extension` being `undefined`, regardless of whether the actual extension is installed.
```typescript
const extension = getReduxExtension(false);
// extension will be undefined regardless of installation
```
--------------------------------
### Update Jotai DevTools Imports
Source: https://github.com/jotaijs/jotai-devtools/blob/main/README.md
Illustrates updating import paths from 'jotai/react/devtools' to 'jotai-devtools' for Jotai DevTools.
```diff
import {
useAtomsSnapshot,
useGotoAtomsSnapshot,
useAtomsDebugValue,
// Redux devtool integration hooks
useAtomDevtools,
useAtomsDevtools,
- } from 'jotai/react/devtools';
+ } from 'jotai-devtools';
```
--------------------------------
### Basic Usage: Track All Atom Values
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/useatomssnapshot.md
This snippet demonstrates how to use useAtomsSnapshot to retrieve and display the values of all mounted atoms. It's useful for a general overview of your application's atom state.
```typescript
import { useAtomsSnapshot } from 'jotai-devtools';
import { atom, useAtom } from 'jotai';
const countAtom = atom(0);
const nameAtom = atom('Alice');
export function DebugComponent() {
const snapshot = useAtomsSnapshot();
return (
);
}
```
--------------------------------
### Import Jotai DevTools Utilities
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/QUICK_REFERENCE.md
Import utility functions for integrating with Redux DevTools and composing store enhancers. These are useful for advanced configurations and debugging.
```typescript
import {
getReduxExtension,
createReduxConnection,
} from 'jotai-devtools/utils';
import {
isDevToolsStore,
composeWithDevTools,
} from 'jotai-devtools/utils/internals/compose-with-devtools';
```
--------------------------------
### Use Custom Jotai Store
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/configuration.md
Pass a custom Jotai store to debug that specific store instance. This must match the store used by your app's .
```typescript
import { createStore } from 'jotai';
const customStore = createStore();
```
--------------------------------
### CSP Policy Configuration
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/configuration.md
Configure Content Security Policy for Jotai DevTools by setting style-src and script-src directives, then passing the nonce.
```plaintext
Content-Security-Policy:
style-src 'self' 'nonce-{random-value}';
script-src 'self';
```
```typescript
```
--------------------------------
### Tree-shaking DevTools with Next.js for Production
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/devtools-component.md
Implements tree-shaking for DevTools in Next.js production builds using dynamic imports and a separate component file.
```typescript
import 'jotai-devtools/styles.css';
export { DevTools } from 'jotai-devtools';
```
```typescript
import dynamic from 'next/dynamic';
import type { ComponentType } from 'react';
import type { DevToolsProps } from 'jotai-devtools';
let DevToolsComponent: ComponentType | null = null;
if (process.env.NODE_ENV !== 'production') {
DevToolsComponent = dynamic(
() => import('./DevTools').then((mod) => ({ default: mod.DevTools })),
{ ssr: false }
);
}
export function App() {
return (
<>
{DevToolsComponent && }
{/* Your app components */}
>
);
}
```
--------------------------------
### Compose Jotai Store with DevTools
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/store-composition.md
Wraps a Jotai store instance with developer methods for debugging. Use this to enable introspection and time-travel capabilities.
```typescript
export const composeWithDevTools = (
store: Store,
): typeof store | WithDevToolsStore;
```
--------------------------------
### Import Jotai DevTools CSS
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/QUICK_REFERENCE.md
Import the necessary CSS file to style the DevTools panel. This import ensures the UI components are displayed correctly.
```typescript
import 'jotai-devtools/styles.css';
```
--------------------------------
### Configure Custom Store
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/QUICK_REFERENCE.md
When using a custom store, ensure it is consistently applied to both the Jotai `Provider` and the `DevTools` component. This synchronizes the DevTools with your application's state.
```typescript
```
--------------------------------
### Next.js with CSP Configuration
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/configuration.md
Configure Jotai DevTools for Next.js applications with Content Security Policy, including nonce handling in next.config.js and component usage.
```typescript
// next.config.js
const nextConfig = {
transpilePackages: ['jotai-devtools'],
headers: async () => [
{
source: '/:path*',
headers: [
{
key: 'Content-Security-Policy',
value: `style-src 'self' 'nonce-${randomNonce}'`,
},
],
},
],
};
// In your component
```
--------------------------------
### Undo/Redo System Implementation
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/api-reference/usegotoatomssnapshot.md
Implements an undo/redo system by managing a history of atom snapshots. Records the current state, allows undoing to previous states, and redoing to future states using useGotoAtomsSnapshot.
```typescript
import { useAtomsSnapshot, useGotoAtomsSnapshot } from 'jotai-devtools';
import { useCallback, useState } from 'react';
export function UndoRedoExample() {
const snapshot = useAtomsSnapshot();
const goToSnapshot = useGotoAtomsSnapshot();
const [history, setHistory] = useState([]);
const [currentIndex, setCurrentIndex] = useState(-1);
const recordSnapshot = useCallback(() => {
const newHistory = history.slice(0, currentIndex + 1);
newHistory.push(snapshot);
setHistory(newHistory);
setCurrentIndex(newHistory.length - 1);
}, [snapshot, history, currentIndex]);
const undo = useCallback(() => {
if (currentIndex > 0) {
const newIndex = currentIndex - 1;
goToSnapshot(history[newIndex]);
setCurrentIndex(newIndex);
}
}, [currentIndex, history, goToSnapshot]);
const redo = useCallback(() => {
if (currentIndex < history.length - 1) {
const newIndex = currentIndex + 1;
goToSnapshot(history[newIndex]);
setCurrentIndex(newIndex);
}
}, [currentIndex, history, goToSnapshot]);
return (
);
}
```
--------------------------------
### Store Composition API
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/MANIFEST.md
APIs for composing and managing Jotai stores, including integration with development tools.
```APIDOC
## Store Composition API
### Description
This section details the functions and types related to composing and managing Jotai stores, particularly focusing on how to integrate them with development tools like Jotai DevTools.
### Functions
#### `composeWithDevTools`
- **Description**: Composes a store with development tool capabilities.
- **Parameters**:
- `store` (Store) - The Jotai store to compose.
- `options` (object) - Configuration options for the DevTools integration.
- `name` (string) - Name of the store in DevTools.
- `enabled` (boolean) - Whether to enable DevTools.
- **Return Type**: `WithDevToolsStore`
#### `isDevToolsStore`
- **Description**: Type guard to check if a store is enhanced with DevTools.
- **Parameters**:
- `store` (Store) - The store to check.
- **Return Type**: `boolean`
### Types
- **`Store`**: Represents a Jotai store.
- **`WithDevToolsStore`**: A store enhanced with DevTools methods.
- **`StoreWithDevMethods`**: Type for stores with development methods.
- **`StoreWithoutDevMethods`**: Type for stores without development methods.
### Examples
```jsx
import { atom, createStore } from 'jotai';
import { composeWithDevTools, isDevToolsStore } from 'jotai-devtools/utils';
const countAtom = atom(0);
const baseStore = createStore();
// Compose the store with DevTools
const devToolsStore = composeWithDevTools(baseStore, {
name: 'My Composed Store',
enabled: true,
});
// Check if the store has DevTools capabilities
if (isDevToolsStore(devToolsStore)) {
console.log('Store is enhanced with DevTools');
}
```
```
--------------------------------
### Set Initial DevTools State
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/configuration.md
Set to true to show the DevTools panel on page load. Defaults to false (closed with only the trigger button visible).
```typescript
```
--------------------------------
### Production-Ready DevTools with Tree-Shaking
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/OVERVIEW.md
Conditionally render the DevTools component only in development environments to leverage tree-shaking and minimize production bundle size. Configure snapshot history limit.
```typescript
const isDev = process.env.NODE_ENV === 'development';
function App() {
return (
<>
{isDev && }
{/* App */}
>
);
}
```
--------------------------------
### Set DevTools Theme
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/configuration.md
Sets the color scheme for the DevTools. Omit this prop to use system preference or a stored localStorage value.
```typescript
```
--------------------------------
### Importing Jotai DevTools Types
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/types.md
Shows how to import various types from the 'jotai-devtools' package for use in TypeScript projects. This includes types for stores, atoms, snapshots, and options.
```typescript
import type {
Store,
DevStore,
AnyAtom,
AnyAtomValue,
AtomsSnapshot,
AtomsValues,
AtomsDependents,
DevToolsOptions,
Options,
WithInitialValue,
} from 'jotai-devtools';
```
--------------------------------
### Next.js Configuration for Jotai DevTools
Source: https://github.com/jotaijs/jotai-devtools/blob/main/README.md
Configure next.config.ts to transpile Jotai DevTools packages for correct CSS and component rendering in Next.js applications.
```ts
// next.config.ts
const nextConfig = {
// Learn more here - https://nextjs.org/docs/advanced-features/compiler#module-transpilation
// Required for font css to be imported correctly 👇
transpilePackages: ['jotai-devtools'],
};
module.exports = nextConfig;
```
--------------------------------
### Options Type for useStore
Source: https://github.com/jotaijs/jotai-devtools/blob/main/_autodocs/types.md
Defines the options that can be passed to the useStore hook. It is a parameter type for useStore.
```typescript
export type Options = Parameters[0];
```