Home >Web Front-end >JS Tutorial >Reactive State Management Without Libraries

Reactive State Management Without Libraries

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-24 00:36:09693browse

Reactive State Management Without Libraries

Simple and powerful status processing

<code class="language-javascript">export class State<IState extends Record<string, unknown>> {
    private data = new Map<keyof IState, IState[keyof IState]>();
    private subscribers = new Map<string, ((...args: any[]) => void)[]>();

    set(name: keyof IState, value: IState[keyof IState]): void {
        this.data.set(name, value);
        this.publish(`change:${String(name)}`, value);
    }

    get(name: keyof IState): IState[keyof IState] | undefined {
        return this.data.get(name);
    }

    has(name: keyof IState): boolean {
        return this.data.has(name);
    }

    clear(): void {
        this.data.clear();
        this.publish('clear');
    }

    publish(name: string, ...args: any[]): void {
        this.subscribers.get(name)?.forEach(fn => fn(...args));
    }

    subscribe(name: string, fn: (...args: any[]) => void): void {
        this.subscribers.has(name)
            ? this.subscribers.get(name)!.push(fn)
            : this.subscribers.set(name, [fn]);
    }

    unsubscribe(name: string, fn: (...args: any[]) => void): void {
        if (this.subscribers.has(name)) {
            const idx = this.subscribers.get(name)!.indexOf(fn);
            if (idx > -1) this.subscribers.get(name)!.splice(idx, 1);
        }
    }

    unsubscribeAll(name: string): void {
        this.subscribers.delete(name);
    }
}</code>

Data Binding: True Responsiveness

React integration example

<code class="language-javascript">function UserProfile() {
    const state = new State();

    const [userData, setUserData] = useState({
        name: state.get('name') || '',
        age: state.get('age') || 0
    });

    // 通过状态变化实现自动响应
    state.subscribe('change:name', (newName) => {
        setUserData(prev => ({ ...prev, name: newName }));
    });

    return (
        <div>
            <input type="text" onChange={e => state.set('name', e.target.value)} />
        </div>
    );
}</code>

Why it’s better than reactive libraries

  • Zero external dependencies
  • Minimized package size
  • Native JavaScript performance
  • Simple and intuitive API
  • Built-in change tracking

Key responsive principles

  1. Status changes trigger updates
  2. Automatically notify subscribers
  3. No need for complex stream processing
  4. Direct, predictable data flow

Conclusion

Reactive is not dependent on libraries. It's about understanding how data flows and changes. This implementation proves that powerful state management is native to JavaScript.

The above is the detailed content of Reactive State Management Without Libraries. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn