### getNewOutlet Example (JavaScript)
Source: https://github.com/revtel/reconnect.js/blob/master/doc/docs/primitive-api.md
Demonstrates how to use `getNewOutlet` to create a persistent outlet for a 'value' and provides an example of how to update it. It also shows how to expose a function to the browser's window object for external manipulation.
```javascript
const ValueOutlet = getNewOutlet('value', 0, {autoDelete: false});
if (typeof window !== undefined) {
// so you can call it from browser's inspector
window.addOne = () => {
ValueOutlet.update(ValueOutlet.getValue() + 1);
};
}
```
--------------------------------
### Reconnect.js Basic Usage Example
Source: https://github.com/revtel/reconnect.js/blob/master/doc/docs/intro.md
This JavaScript code snippet demonstrates the fundamental usage of Reconnect.js for sharing state between React components. It utilizes `useOutletDeclaration`, `useOutlet`, and `useOutletSetter` hooks to manage and update a shared 'add' state across different components, including sibling and nested ones. No external dependencies beyond React and Reconnect.js are required for this basic setup.
```javascript
import React from 'react';
import {useOutlet, useOutletSetter, useOutletDeclaration} from 'reconnect.js';
function App() {
useOutletDeclaration('add', 0);
return (
);
}
function Value() {
const [value] = useOutlet('add');
return
{value}
;
}
function ActionBar(props) {
return (
);
}
function Add() {
const [value, setValue] = useOutlet('add');
return ;
}
function Sub() {
const [_, setValue] = useOutlet('add');
return ;
}
function Reset() {
const setValue = useOutletSetter('add');
return ;
}
export default App;
```
--------------------------------
### Example Usage of getNewOutlet (JavaScript)
Source: https://github.com/revtel/reconnect.js/blob/master/README.md
Demonstrates creating an outlet named 'value' with an initial value of 0 and `autoDelete: false`. It also shows how to expose an `addOne` function to the browser's console for manual updates and how a `Value` component can consume this outlet.
```javascript
const ValueOutlet = getNewOutlet('value', 0, {autoDelete: false});
if (typeof window !== undefined) {
// so you can call it from browser's inspector
window.addOne = () => {
ValueOutlet.update(ValueOutlet.getValue() + 1);
};
}
function App() {
return (
);
}
function Value() {
const [value] = useOutlet('value');
return
{value}
;
}
```
--------------------------------
### useOutlet Hook Example (JavaScript)
Source: https://github.com/revtel/reconnect.js/blob/master/doc/docs/primitive-api.md
Illustrates the usage of a `useOutlet` hook (presumably from Reconnect.js) within a React component to subscribe to an outlet's value. The component re-renders automatically when the outlet's value changes.
```javascript
function App() {
return (
);
}
function Value() {
const [value] = useOutlet('value');
return
{value}
;
}
```
--------------------------------
### Example Usage of useOutletSelector (JavaScript)
Source: https://github.com/revtel/reconnect.js/blob/master/README.md
Shows how to use `useOutletSelector` to get a partial value from an outlet. A selector function is defined using `React.useCallback` to extract `state.inner.value` from the outlet identified by the key 'test'.
```javascript
function PartialValue() {
const selector = React.useCallback(state => state.inner.value, []);
const partialValue = useOutletSelector('test', selector);
return (
{partialValue}
)
}
```
--------------------------------
### Example Usage of useOutletDeclaration (JavaScript)
Source: https://github.com/revtel/reconnect.js/blob/master/README.md
Demonstrates how to use `useOutletDeclaration` in an App component to declare an outlet named 'add'. Child components `Value` and `Add` then use the `useOutlet` hook to access and modify the outlet's value.
```javascript
function App() {
useOutletDeclaration('add', 0);
return (
;
}
```
--------------------------------
### Outlet Interface Definition (TypeScript)
Source: https://github.com/revtel/reconnect.js/blob/master/doc/docs/primitive-api.md
Defines the structure and methods of an Outlet, which allows producers and consumers to publish or subscribe to value changes. It includes methods for registering listeners, updating values, and getting the current value.
```typescript
export interface Outlet {
/**
* Subscribe to value changes.
*
* @param handler - The value change listener function
* @returns A function to unregister the value change
*/
register: (handler: valueChangeListener) => unregisterOutlet;
/**
* Change the value backed by this outlet and publish to all subscribers.
*
* @param value - The value you'd like to change or a callback function to produce the value.
*/
update: (value: nextValueOrGetter) => void;
/**
* Get the value backed by this outlet
*/
getValue: () => T;
}
```
--------------------------------
### Outlet Interface Definition (TypeScript)
Source: https://github.com/revtel/reconnect.js/blob/master/README.md
Defines the `Outlet` interface, which represents a mechanism for publishing and subscribing to value changes. It includes methods for registering listeners, updating values, getting the current value, and checking subscriber counts.
```typescript
export interface Outlet {
/**
* Subscribe to value changes.
*
* @param handler - The value change listener function
* @returns A function to unregister the value change
*/
register: (handler: valueChangeListener) => unregisterOutlet;
/**
* Change the value backed by this outlet and publish to all subscribers.
*
* @param value - The value you'd like to change or a callback function to produce the value.
*/
update: (value: nextValueOrGetter) => void;
/**
* Get the value backed by this outlet
*/
getValue: () => T;
/**
* Get the subscribers count for this outlet
*/
getRefCnt: () => number;
}
```
--------------------------------
### Create and Use Event Bus with reconnect.js
Source: https://context7.com/revtel/reconnect.js/llms.txt
This snippet demonstrates how to implement a publish-subscribe event bus using reconnect.js's `getNewOutlet`. It allows for emitting events with payloads and subscribing to these events. The `EventBus` class provides methods to `emit`, `subscribe`, `getHistory`, `clear`, and `getSubscriberCount`. This pattern is useful for decoupling services and handling cross-component communication.
```javascript
import { getNewOutlet } from 'reconnect.js';
// Create event bus using outlet
const eventBus = getNewOutlet('events', [], { autoDelete: false });
class EventBus {
static emit(eventName, payload) {
eventBus.update(prev => [...prev, {
name: eventName,
payload,
timestamp: Date.now()
}]);
}
static subscribe(handler) {
return eventBus.register((events) => {
const latestEvent = events[events.length - 1];
if (latestEvent) {
handler(latestEvent);
}
});
}
static getHistory() {
return eventBus.getValue();
}
static clear() {
eventBus.update([]);
}
static getSubscriberCount() {
return eventBus.getRefCnt();
}
}
// Usage in services
class AnalyticsService {
constructor() {
// Subscribe to events
this.unsubscribe = EventBus.subscribe((event) => {
console.log('Tracking:', event);
this.track(event.name, event.payload);
});
}
track(eventName, data) {
fetch('/api/analytics', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ event: eventName, data, timestamp: Date.now() })
});
}
cleanup() {
this.unsubscribe();
}
}
// Emit events from anywhere
EventBus.emit('user.login', { userId: 123 });
EventBus.emit('page.view', { path: '/dashboard' });
console.log(EventBus.getSubscriberCount()); // 1
console.log(EventBus.getHistory()); // Array of all events
const analytics = new AnalyticsService();
// Events are automatically tracked
```
--------------------------------
### Reconnect.js useOutlet Hook: Creating and Using Outlets
Source: https://github.com/revtel/reconnect.js/blob/master/README.md
Illustrates the `useOutlet` hook from Reconnect.js, showing how to both create a new outlet with an initial value and access an existing outlet. This hook provides a state-like interface (`[value, setValue]`) for shared data.
```javascript
// Use a new outlet with an initial value
function Add() {
const [value, setValue] = useOutlet('add', 0);
return ;
}
// Use an already existed outlet
function Add() {
const [value, setValue] = useOutlet('add');
return ;
}
```
--------------------------------
### Access and Modify Outlets with getOutlet in JavaScript
Source: https://context7.com/revtel/reconnect.js/llms.txt
Shows how to retrieve an existing outlet using `getOutlet` from `reconnect.js`, or a `NullOutlet` if it doesn't exist. This function is crucial for interacting with state managed by `reconnect.js` from various parts of an application, including service layers. It also demonstrates using `hasOutlet` to check for existence before accessing. Dependencies include `reconnect.js`.
```javascript
import { getOutlet, getNewOutlet, hasOutlet } from 'reconnect.js';
// Initialize application state
function initializeApp() {
getNewOutlet('appState', {
isInitialized: false,
currentUser: null,
features: []
}, { autoDelete: false });
}
// Service layer can check and update outlets
class AuthService {
static login(username, password) {
return fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
})
.then(res => res.json())
.then(user => {
// Check if outlet exists before updating
if (hasOutlet('appState')) {
const outlet = getOutlet('appState');
outlet.update(prev => ({
...prev,
currentUser: user,
isInitialized: true
}));
}
return user;
});
}
static logout() {
const outlet = getOutlet('appState');
outlet.update(prev => ({
...prev,
currentUser: null
}));
}
static getCurrentUser() {
const outlet = getOutlet('appState');
const state = outlet.getValue();
return state.currentUser;
}
}
// Initialize on app start
initializeApp();
export { AuthService };
```
--------------------------------
### Outlet Options Interface (TypeScript)
Source: https://github.com/revtel/reconnect.js/blob/master/doc/docs/primitive-api.md
Defines the options available when creating a new outlet. The primary option is `autoDelete`, which controls whether the outlet is automatically removed when it has no subscribers.
```typescript
export interface OutletOptions {
autoDelete?: boolean;
}
```
--------------------------------
### Async State Updates with Reconnect.js Hooks
Source: https://context7.com/revtel/reconnect.js/llms.txt
Handles asynchronous data fetching and state updates using `useOutlet` with an async callback. It automatically manages loading, error, and data states, simplifying UI updates. This pattern is useful for API interactions where immediate feedback is required.
```javascript
import React from 'react';
import { useOutlet, useOutletDeclaration } from 'reconnect.js';
function App() {
useOutletDeclaration('userData', { loading: false, data: null, error: null });
return (
);
}
function UserProfile() {
const [userData] = useOutlet('userData');
if (userData.loading) return
);
}
function LoadUserButton() {
const [, setUserData] = useOutlet('userData');
const loadUser = async (userId) => {
// Set loading state
setUserData({ loading: true, data: null, error: null });
// Async callback function - automatically updates when promise resolves
setUserData(async (prev) => {
try {
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) throw new Error('Failed to fetch user');
const data = await response.json();
return { loading: false, data, error: null };
} catch (error) {
return { loading: false, data: null, error: error.message };
}
});
};
return (
);
}
export default App;
```
--------------------------------
### getOutlet
Source: https://github.com/revtel/reconnect.js/blob/master/README.md
Retrieves an existing Outlet instance by its key. If no Outlet is found for the given key, it returns a singleton `NullOutlet`.
```APIDOC
## getOutlet
### Description
Get an existing outlet. If not found, return the `NullOutlet` singleton.
### Signature
```typescript
declare function getOutlet(key: any): Outlet;
```
```
--------------------------------
### Create a New Outlet (TypeScript)
Source: https://github.com/revtel/reconnect.js/blob/master/README.md
Provides a function `getNewOutlet` to create or retrieve an outlet by its key. If an outlet doesn't exist, it's created and registered globally. Options include `autoDelete` to manage automatic removal when subscribers drop to zero.
```typescript
export interface OutletOptions {
autoDelete?: boolean;
}
declare function getNewOutlet(
key: any,
initialValue: initialValueOrGetter,
options?: OutletOptions
): Outlet;
```
--------------------------------
### useOutlet Hook for Managing Outlet State
Source: https://github.com/revtel/reconnect.js/blob/master/doc/docs/react-hook-api.md
The `useOutlet` hook provides a key-value store for managing state across components. It returns the current value and a setter function, similar to `React.useState`. It can initialize new outlets with an `initialValue` or retrieve existing ones. The setter also accepts callbacks for value updates. Options can be passed for advanced outlet behavior.
```typescript
declare function useOutlet(
key: any,
initialValue?: initialValueOrGetter,
options?: OutletOptions,
): [T, (value: nextValueOrGetter) => void];
```
```javascript
function Add() {
const [value, setValue] = useOutlet('add', 0);
return ;
}
```
```javascript
function Add() {
const [value, setValue] = useOutlet('add');
return ;
}
```
--------------------------------
### Optimize Re-renders with useOutletSelector in React
Source: https://context7.com/revtel/reconnect.js/llms.txt
Demonstrates how `useOutletSelector` from `reconnect.js` allows components to subscribe to only specific parts of an outlet's state. This minimizes re-renders when unrelated state changes occur. It requires `react` and `reconnect.js`.
```javascript
import React from 'react';
import { useOutlet, useOutletSelector, useOutletSetter, useOutletDeclaration } from 'reconnect.js';
function App() {
useOutletDeclaration('userProfile', {
personal: { name: 'John', age: 30 },
settings: { notifications: true, theme: 'dark' },
stats: { posts: 42, followers: 100 }
});
return (
);
}
function PersonalInfo() {
// Only re-renders when personal.name changes
const selector = React.useCallback(state => state.personal.name, []);
const name = useOutletSelector('userProfile', selector);
console.log('PersonalInfo rendered');
return
Name: {name}
;
}
function Settings() {
// Only re-renders when settings.theme changes
const selector = React.useCallback(state => state.settings.theme, []);
const theme = useOutletSelector('userProfile', selector);
return
Theme: {theme}
;
}
function Stats() {
// Only re-renders when stats.followers changes
const selector = React.useCallback(state => state.stats.followers, []);
const followers = useOutletSelector('userProfile', selector);
return
Followers: {followers}
;
}
function UpdateAge() {
const setProfile = useOutletSetter('userProfile');
// PersonalInfo won't re-render since name doesn't change
return (
);
}
```
--------------------------------
### Manage Global State with getNewOutlet in JavaScript
Source: https://context7.com/revtel/reconnect.js/llms.txt
Illustrates how to create and manage a global state outlet outside of React components using `getNewOutlet` from `reconnect.js`. This is useful for managing global concerns like notifications or API service states. It allows direct updates via `.update()` and subscriptions via `useOutlet` in React components. Dependencies include `reconnect.js`.
```javascript
import { getNewOutlet, useOutlet } from 'reconnect.js';
// Create outlet outside component for global access
const notificationOutlet = getNewOutlet('notifications', [], { autoDelete: false });
// API service can update outlet directly
class ApiService {
static async fetchData() {
try {
const response = await fetch('/api/data');
const data = await response.json();
return data;
} catch (error) {
notificationOutlet.update(prev => [...prev, {
id: Date.now(),
type: 'error',
message: error.message
}]);
throw error;
}
}
static clearNotifications() {
notificationOutlet.update([]);
}
}
// Make it accessible in browser console for debugging
if (typeof window !== 'undefined') {
window.addNotification = (message) => {
notificationOutlet.update(prev => [...prev, {
id: Date.now(),
type: 'info',
message
}]);
};
}
// React component subscribes to outlet
function NotificationCenter() {
const [notifications] = useOutlet('notifications');
return (
{notifications.map(notif => (
{notif.message}
))}
);
}
export { ApiService, NotificationCenter };
```
--------------------------------
### Outlet API
Source: https://github.com/revtel/reconnect.js/blob/master/README.md
Defines the structure and behavior of an Outlet, which allows for publishing and subscribing to value changes within the Reconnect.js state management system.
```APIDOC
## Primitive API - Outlet
### Description
An outlet let producers or consumers to publish or subscribe value changes.
### Signature
```typescript
export interface Outlet {
/**
* Subscribe to value changes.
*
* @param handler - The value change listener function
* @returns A function to unregister the value change
*/
register: (handler: valueChangeListener) => unregisterOutlet;
/**
* Change the value backed by this outlet and publish to all subscribers.
*
* @param value - The value you'd like to change or a callback function to produce the value.
*/
update: (value: nextValueOrGetter) => void;
/**
* Get the value backed by this outlet
*/
getValue: () => T;
/**
* Get the subscribers count for this outlet
*/
getRefCnt: () => number;
}
```
```
--------------------------------
### Use Outlet Hook for State Management in React
Source: https://context7.com/revtel/reconnect.js/llms.txt
The useOutlet hook allows components to subscribe to and update outlet state, functioning similarly to React.useState. It requires importing 'useOutlet' and 'useOutletDeclaration' from 'reconnect.js'. It takes an outlet name and returns a state value and a setter function.
```javascript
import React from 'react';
import { useOutlet, useOutletDeclaration } from 'reconnect.js';
function App() {
// Declare outlet at root level
useOutletDeclaration('counter', 0);
return (
);
}
function Display() {
const [count] = useOutlet('counter');
return
);
}
```
--------------------------------
### useOutletSetter Hook
Source: https://github.com/revtel/reconnect.js/blob/master/README.md
The `useOutletSetter` hook provides only the setter function for an outlet, optimizing components that only need to modify the state without re-rendering when the state changes.
```APIDOC
## useOutletSetter Hook
### Description
Provides only the setter function for an outlet. This is useful for components that need to modify the outlet's state but should not re-render when the state itself changes.
### Signature
```typescript
declare function useOutletSetter(
key: any,
): (value: nextValueOrGetter) => void;
```
### Parameters
#### Path Parameters
- **key** (any) - Required - A unique identifier for the outlet.
### Request Example
```javascript
function ResetValue() {
const setValue = useOutletSetter('add');
return ;
}
```
### Response
#### Success Response (200)
- **setValue** ((value: T | (prevValue: T) => T) => void) - A function to update the outlet's value. Accepts a new value or a function that receives the previous value and returns the new value.
#### Response Example
```json
{
"setValue": "function"
}
```
```
--------------------------------
### Use Outlet Setter Hook for State Updates in React
Source: https://context7.com/revtel/reconnect.js/llms.txt
The useOutletSetter hook provides only the setter function for an outlet, enabling state updates without subscribing to value changes. This prevents unnecessary re-renders in components that only need to modify state. It requires importing 'useOutletSetter', 'useOutlet', and 'useOutletDeclaration' from 'reconnect.js'.
```javascript
import React from 'react';
import { useOutlet, useOutletSetter, useOutletDeclaration } from 'reconnect.js';
function App() {
useOutletDeclaration('tasks', []);
return (
);
}
function AddTaskForm() {
const [input, setInput] = React.useState('');
const setTasks = useOutletSetter('tasks');
const handleSubmit = (e) => {
e.preventDefault();
if (input.trim()) {
setTasks(prev => [...prev, input]);
setInput('');
}
};
return (
);
}
function ClearButton() {
// Only uses setter, won't re-render when tasks change
const setTasks = useOutletSetter('tasks');
return ;
}
```
--------------------------------
### useOutletDeclaration Hook
Source: https://github.com/revtel/reconnect.js/blob/master/README.md
The `useOutletDeclaration` hook is used to declare and optionally initialize an outlet. It ensures that an outlet exists with a specified key and initial value.
```APIDOC
## useOutletDeclaration Hook
### Description
Declares an outlet, optionally initializing it with a value. This hook is typically used at a higher level in the component tree to ensure an outlet is available.
### Signature
```typescript
declare function useOutletDeclaration(
key: any,
initialValue?: initialValueOrGetter,
options?: OutletOptions,
): void;
```
### Parameters
#### Path Parameters
- **key** (any) - Required - A unique identifier for the outlet.
- **initialValue** (T | () => T) - Optional - The initial value for the outlet.
- **options** (OutletOptions) - Optional - Advanced options for outlet behavior.
### Request Example
```javascript
function App() {
useOutletDeclaration('add', 0);
return (
{/* Components that use the 'add' outlet */}
);
}
```
### Response
This hook does not return any value. Its purpose is to declare and potentially initialize the outlet.
```
--------------------------------
### getNewOutlet Function Signature (TypeScript)
Source: https://github.com/revtel/reconnect.js/blob/master/doc/docs/primitive-api.md
Declares the function signature for `getNewOutlet`, used to obtain or create an outlet with a specified key. It supports an initial value or a getter function for it, and optional configuration like `autoDelete`.
```typescript
declare function getNewOutlet(
key: any,
initialValue: initialValueOrGetter,
options?: OutletOptions,
): Outlet;
```
--------------------------------
### useOutlet Hook
Source: https://github.com/revtel/reconnect.js/blob/master/README.md
The `useOutlet` hook provides both the current value of an outlet and a function to set its new value. It can also initialize a new outlet if an `initialValue` is provided.
```APIDOC
## useOutlet Hook
### Description
Provides access to an outlet's value and a setter function. If `initialValue` is provided, it initializes a new outlet; otherwise, it retrieves an existing one.
### Signature
```typescript
declare function useOutlet(
key: any,
initialValue?: initialValueOrGetter,
options?: OutletOptions,
): [T, (value: nextValueOrGetter) => void];
```
### Parameters
#### Path Parameters
- **key** (any) - Required - A unique identifier for the outlet.
- **initialValue** (T | () => T) - Optional - The initial value for the outlet if it doesn't exist. Can be a value or a function that returns a value.
- **options** (OutletOptions) - Optional - Advanced options for outlet behavior.
### Request Example
Use a new outlet with an initial value:
```javascript
function Add() {
const [value, setValue] = useOutlet('add', 0);
return ;
}
```
Use an already existing outlet:
```javascript
function Add() {
const [value, setValue] = useOutlet('add');
return ;
}
```
### Response
#### Success Response (200)
- **value** (T) - The current value of the outlet.
- **setValue** ((value: T | (prevValue: T) => T) => void) - A function to update the outlet's value. Accepts a new value or a function that receives the previous value and returns the new value.
#### Response Example
```json
{
"value": 10,
"setValue": "function"
}
```
```
--------------------------------
### getNewOutlet
Source: https://github.com/revtel/reconnect.js/blob/master/README.md
Creates and returns a new Outlet instance associated with a given key. If an outlet for the key already exists, it returns the existing one. Supports an option to automatically delete the outlet when it has no subscribers.
```APIDOC
## getNewOutlet
### Description
Get or create an outlet using given key. This method first search global registry to see if the key has a corresponding outlet, if so returns it. Otherwise it will create a new outlet and set to global registry, then returns it. The `initialValue` can be a callback function, which returns the actual value. The `options` has a property `autoDelete`, which indicates whether `Reconnect.js` should automatically remove the outlet when the number of subscribers down to 0. The default value is `true`, but when you create outlets explicitly by calling `getNewOutlet`, you should set it to false.
### Signature
```typescript
export interface OutletOptions {
autoDelete?: boolean;
}
declare function getNewOutlet(
key: any,
initialValue: initialValueOrGetter,
options?: OutletOptions,
): Outlet;
```
### Example
```javascript
const ValueOutlet = getNewOutlet('value', 0, {autoDelete: false});
if (typeof window !== undefined) {
// so you can call it from browser's inspector
window.addOne = () => {
ValueOutlet.update(ValueOutlet.getValue() + 1);
};
}
function App() {
return (
);
}
function Value() {
const [value] = useOutlet('value');
return
{value}
;
}
```
```
--------------------------------
### isNull
Source: https://github.com/revtel/reconnect.js/blob/master/README.md
Tests if a given Outlet instance is the `NullOutlet` singleton. This API is typically not needed for regular application development.
```APIDOC
## isNull
### Description
Test if the outlet is NullOutlet singleton. Normally applications don't need to call this API.
### Signature
```typescript
declare function isNull(outlet: Outlet): boolean;
```
```
--------------------------------
### Test for NullOutlet Singleton (TypeScript)
Source: https://github.com/revtel/reconnect.js/blob/master/README.md
Checks if a given outlet is the `NullOutlet` singleton. This is typically an internal API not required for most application-level usage.
```typescript
declare function isNull(outlet: Outlet): boolean;
```
--------------------------------
### hasOutlet
Source: https://github.com/revtel/reconnect.js/blob/master/README.md
Checks if an Outlet with the specified key currently exists in the registry.
```APIDOC
## hasOutlet
### Description
Check if the outlet already exists.
### Signature
```typescript
declare function hasOutlet(key: any): boolean;
```
```
--------------------------------
### getOutlet Function Signature (TypeScript)
Source: https://github.com/revtel/reconnect.js/blob/master/doc/docs/primitive-api.md
Declares the function signature for `getOutlet`, which retrieves an existing outlet by its key. If the outlet is not found, this function is expected to throw an `OutletNotFoundError`.
```typescript
declare function getOutlet(key: any): Outlet;
```
--------------------------------
### useOutletDeclaration Hook for Outlet Initialization
Source: https://github.com/revtel/reconnect.js/blob/master/doc/docs/react-hook-api.md
The `useOutletDeclaration` hook declares an outlet with an initial value without accessing its state. If the outlet doesn't exist, it will be created. This is beneficial for root components that need to establish an outlet for child components but do not require direct access to the state, preventing re-renders when the state changes.
```typescript
declare function useOutletDeclaration(
key: any,
initialValue: initialValueOrGetter,
): void;
```
```javascript
function App() {
useOutletDeclaration('add', 0);
return (
;
}
```
--------------------------------
### useOutletSetter Hook for State Updates
Source: https://github.com/revtel/reconnect.js/blob/master/doc/docs/react-hook-api.md
The `useOutletSetter` hook provides only the setter function for an outlet. This is useful when a component only needs to modify the state without needing to re-render when the state changes, optimizing performance by avoiding unnecessary re-renders.
```typescript
declare function useOutletSetter(
key: any,
): (value: nextValueOrGetter) => void;
```
```javascript
function ResetValue() {
const setValue = useOutletSetter('add');
return ;
}
```
--------------------------------
### hasOutlet Function Signature (TypeScript)
Source: https://github.com/revtel/reconnect.js/blob/master/doc/docs/primitive-api.md
Declares the function signature for `hasOutlet`, a utility function that checks for the existence of an outlet associated with a given key in the global registry.
```typescript
declare function hasOutlet(key: any): boolean;
```
--------------------------------
### Force Remove Outlet with reconnect.js
Source: https://context7.com/revtel/reconnect.js/llms.txt
The `removeOutlet` function in reconnect.js allows for the forceful removal of an outlet from the global registry. This is useful in scenarios like test environment cleanup or hot module replacement, where an outlet might need to be removed even if it still has active subscribers. The `force` parameter (boolean) determines whether to proceed with removal despite active subscriptions.
```javascript
import { getNewOutlet, removeOutlet, hasOutlet, getOutlet } from 'reconnect.js';
// Test environment cleanup utility
class TestHelper {
static outlets = new Set();
static createTestOutlet(key, initialValue) {
this.outlets.add(key);
return getNewOutlet(key, initialValue, { autoDelete: false });
}
static cleanupAll() {
this.outlets.forEach(key => {
if (hasOutlet(key)) {
removeOutlet(key, true); // Force remove even with subscribers
}
});
this.outlets.clear();
}
}
// Test suite
describe('User Component', () => {
beforeEach(() => {
TestHelper.createTestOutlet('testUser', { name: 'Test', email: 'test@example.com' });
});
afterEach(() => {
TestHelper.cleanupAll();
});
test('should display user name', () => {
// Test implementation
expect(hasOutlet('testUser')).toBe(true);
});
});
// Production cleanup on hot reload
if (module.hot) {
module.hot.dispose(() => {
['tempData', 'cache', 'session'].forEach(key => {
if (hasOutlet(key)) {
const outlet = getOutlet(key);
if (outlet.getRefCnt() === 0) {
removeOutlet(key);
}
}
});
});
}
```
--------------------------------
### useOutletDeclaration
Source: https://github.com/revtel/reconnect.js/blob/master/README.md
Declares an outlet for child components without causing re-renders in the parent when the outlet's value changes. Useful for initializing outlets that are primarily managed by child components.
```APIDOC
## useOutletDeclaration
### Description
Declare an outlet without using its value and setter. If the outlet doesn't exist yet, create it. It's useful when you want to declare an outlet for your child components, but the root component itself doesn't need either value and setter, so when the value is changed, the root component won't re-render.
### Signature
```typescript
declare function useOutletDeclaration(
key: any,
initialValue: initialValueOrGetter
): void;
```
### Example
```javascript
function App() {
useOutletDeclaration('add', 0);
return (
;
}
```
```
--------------------------------
### Declare Outlets at Root Level in React with useOutletDeclaration
Source: https://context7.com/revtel/reconnect.js/llms.txt
The useOutletDeclaration hook allows declaring outlets at the root component level without subscribing to their state changes. This prevents the root component from re-rendering when outlet values are updated. It requires importing 'useOutlet' and 'useOutletDeclaration' from 'reconnect.js'.
```javascript
import React from 'react';
import { useOutlet, useOutletDeclaration } from 'reconnect.js';
function App() {
// Declare outlets without subscribing - App won't re-render when values change
useOutletDeclaration('username', 'Guest');
useOutletDeclaration('theme', 'light');
console.log('App rendered'); // Only logs once on mount
return (
);
}
```
--------------------------------
### Select Partial State from Outlet (TypeScript)
Source: https://github.com/revtel/reconnect.js/blob/master/README.md
Retrieves a portion of an outlet's state using a selector function. Components using this hook only re-render when the selected value changes, optimizing performance. The selector function should be memoized with React.useCallback.
```typescript
declare function useOutletSelector(key: any, selector: (state: T) => U): U;
```
--------------------------------
### removeOutlet Function Signature (TypeScript)
Source: https://github.com/revtel/reconnect.js/blob/master/doc/docs/primitive-api.md
Declares the function signature for `removeOutlet`, which allows for the explicit removal of an outlet from the global registry using its key. This is a forceful operation.
```typescript
declare function removeOutlet(key: any): void;
```
--------------------------------
### Check Outlet Existence with reconnect.js
Source: https://context7.com/revtel/reconnect.js/llms.txt
The `hasOutlet` function from reconnect.js checks if a given outlet key exists in the global registry. It is crucial for preventing errors when accessing or manipulating outlets, ensuring that operations are only performed on existing state containers. This function is often used in conjunction with `getNewOutlet` or `getOutlet`.
```javascript
import { hasOutlet, getNewOutlet, getOutlet, removeOutlet } from 'reconnect.js';
class StateManager {
static initialize(key, initialValue, options) {
if (!hasOutlet(key)) {
return getNewOutlet(key, initialValue, options);
}
console.warn(`Outlet "${key}" already exists`);
return getOutlet(key);
}
static cleanup(key, force = false) {
if (hasOutlet(key)) {
const outlet = getOutlet(key);
const refCount = outlet.getRefCnt();
if (refCount > 0 && !force) {
console.warn(`Cannot remove "${key}": ${refCount} subscribers remain`);
return false;
}
removeOutlet(key, force);
console.log(`Removed outlet "${key}"`);
return true;
}
return false;
}
static debug() {
const outlets = ['counter', 'user', 'settings', 'notifications'];
const report = {};
outlets.forEach(key => {
if (hasOutlet(key)) {
const outlet = getOutlet(key);
report[key] = {
exists: true,
value: outlet.getValue(),
subscribers: outlet.getRefCnt()
};
} else {
report[key] = { exists: false };
}
});
return report;
}
}
// Usage
StateManager.initialize('appConfig', { version: '1.0.0', env: 'production' });
console.log(StateManager.debug());
// { appConfig: { exists: true, value: {...}, subscribers: 0 } }
StateManager.cleanup('appConfig', true);
console.log(hasOutlet('appConfig')); // false
```
--------------------------------
### useOutletSelector
Source: https://github.com/revtel/reconnect.js/blob/master/README.md
Retrieves a partial piece of state from an outlet using a selector function. Components using this hook will only re-render when the selected value changes, allowing for granular state updates.
```APIDOC
## useOutletSelector
### Description
Get partial state from an outlet by passing a selector function. When a component uses this hook, it will be rendered only when the selected value is changed, which let us uses partial of the outlet state rather than the whole state. When using this hook, the selector passed in should be wrapped with React.useCallback().
### Signature
```typescript
declare function useOutletSelector(key: any, selector: (state: T) => U): U;
```
### Example
```javascript
function PartialValue() {
const selector = React.useCallback(state => state.inner.value, []);
const partialValue = useOutletSelector('test', selector);
return (
{partialValue}
)
}
```
```
--------------------------------
### Reconnect.js useOutletSetter Hook: Accessing State Setters
Source: https://github.com/revtel/reconnect.js/blob/master/README.md
Demonstrates the `useOutletSetter` hook from Reconnect.js. This hook is useful when a component only needs to modify a shared state but not read it, preventing unnecessary re-renders caused by state updates in other parts of the application.
```javascript
function ResetValue() {
const setValue = useOutletSetter('add');
return ;
}
```
--------------------------------
### Force Remove an Outlet (TypeScript)
Source: https://github.com/revtel/reconnect.js/blob/master/README.md
Allows for the explicit removal of an outlet from the global registry using its key. By default, it avoids removing outlets with active subscribers unless the `force` option is set to `true`.
```typescript
declare function removeOutlet(key: any, force?: boolean): void;
```
--------------------------------
### removeOutlet
Source: https://github.com/revtel/reconnect.js/blob/master/README.md
Removes an Outlet from the global registry. By default, it will not remove an Outlet if it still has active subscribers, unless the `force` flag is set to `true`.
```APIDOC
## removeOutlet
### Description
Force remove the outlet from global registry. By default, this function won't remove outlets with remaining subscribers, unless the `force` flag is set to `true`.
### Signature
```typescript
declare function removeOutlet(key: any, force?: boolean): void;
```
```
--------------------------------
### Declare Outlet without Value/Setter (TypeScript)
Source: https://github.com/revtel/reconnect.js/blob/master/README.md
Declares an outlet for child components without needing the value or setter in the root component. This prevents re-renders when the outlet's value changes. It takes a key and an initial value or getter.
```typescript
declare function useOutletDeclaration(
key: any,
initialValue: initialValueOrGetter
): void;
```