npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-scomponent

v2.3.3

Published

Barebones esbuild and test node server implementation. For building

Downloads

367

Readme

react-scomponent

A lightweight state management library for React that provides a simple event-driven approach to managing and synchronizing state across components. react-scomponent introduces an EventHandler class for global state management and an sComponent class that extends React components to seamlessly integrate with the global state.

Table of Contents

Introduction

react-scomponent is a minimalistic state management library designed to simplify state handling in React applications. It leverages an event-driven model to allow components to subscribe to state changes, ensuring that your UI stays in sync with your data without the complexity of larger state management solutions like Redux or MobX.

Features

  • Event-Driven State Management: Subscribe to specific state changes and react accordingly.
  • Global State Synchronization: Share state across components without prop drilling.
  • Local Storage Integration: Optionally persist state between sessions using localStorage.
  • Lightweight and Simple: Minimal overhead and easy to integrate into existing projects.

Installation

You can install react-scomponent via npm:

npm install react-scomponent

Or using yarn:

yarn add react-scomponent

Getting Started

EventHandler

The EventHandler class manages global state and allows components to subscribe to changes in specific state properties.

Importing EventHandler

import { EventHandler } from 'react-scomponent';

Creating an EventHandler Instance

You can create a new instance of EventHandler to manage your application's state:

const state = new EventHandler({
  count: 0,
}, true); // The second parameter enables localStorage persistence
  • Parameters:
    • data (optional): An object containing initial state values.
    • useLocalStorage (optional): A boolean indicating whether to persist state in localStorage.

sComponent

The sComponent class extends React.Component and integrates with the EventHandler to automatically synchronize component state with the global state.

Importing sComponent

import { sComponent } from 'react-scomponent';

Creating an sComponent

class Counter extends sComponent {
  state = {
    count: 0,
  };

  //__statemgr = state //you can also override the default state manager with your own, e.g. to make separate state objects.

  // Your component logic...
}

By extending sComponent, your component automatically subscribes to changes in the global state properties that match its local state keys.

API Reference

EventHandler Class

Methods

  • constructor(data?, useLocalStorage?)
    • Initializes the state with the provided data and sets up localStorage if enabled.
  • setState(updateObj)
    • Merges the updateObj into the current state and triggers events for changed properties.
  • setValue(key, value)
    • Sets a single state property and triggers its event.
  • subscribeEvent(key, onchange)
    • Subscribes to changes of a specific state property.
  • unsubscribeEvent(key, sub?)
    • Unsubscribes from a state property change event.
  • subscribeState(onchange)
    • Subscribes to all state changes.
  • unsubscribeState(sub)
    • Unsubscribes from the state change subscription.
  • getSnapshot()
    • Returns a shallow copy of the current state.
  • updateLocalStorage()
    • Manually updates the localStorage with the current state.
  • restoreLocalStorage(data?)
    • Restores state from localStorage.

Properties

  • data
    • The internal state object.
  • useLocalStorage
    • A boolean indicating if localStorage is used.
  • onRemoved
    • A callback function invoked when a trigger is removed.

sComponent Class

Methods

  • constructor(props)
    • Initializes the component and subscribes to state changes.
  • setState(s)
    • Overrides React's setState to synchronize with the global state.
  • __subscribeComponent(prop, onEvent?)
    • Subscribes the component to a specific state property.
  • __unsubscribeComponent(prop?)
    • Unsubscribes the component from state property changes.
  • __setUseLocalStorage(bool)
    • Enables or disables localStorage usage.

Usage Notes

  • The sComponent automatically subscribes to state properties that match its own state keys.
  • Use doNotSubscribe in props to exclude specific state properties from automatic subscription.

Examples

Counter Example

Setting Up the Global State

// state.js
import { EventHandler } from 'react-scomponent';

export const state = new EventHandler({
  count: 0,
}, true);

Creating the Counter Component

// Counter.js
import React from 'react';
import { sComponent, state } from 'react-scomponent';

export class Counter extends sComponent {
  state = {
    count: 0,
  };

  componentDidMount() {
    setTimeout(()=>{
        this.setState({ count: 1 });
    },1000)
  }

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  decrement = () => {
    this.setState({ count: this.state.count - 1 });
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.increment}>Increment</button>
        <button onClick={this.decrement}>Decrement</button>
      </div>
    );
  }
}

//subscribe in the script anywhere, and it will be synchronized with all sComponents tied to that state object
state.subscribeEvent('count',(ct)=>{
    console.log("Count: " + ct);
});

//e.g. you can interact with the state anywhere and propagate to components
setInterval(()=>{
    state.setState({ count: this.state.count + 1 });
},1000)

Using the Counter Component

// App.js
import React from 'react';
import { Counter } from './Counter';

function App() {
  return (
    <div>
      <h1>Counter Example</h1>
      <Counter />
    </div>
  );
}

export default App;

License

This project is licensed under the MIT License - see the LICENSE file for details.