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-class-state

v1.1.0

Published

Easy State Management For React With Classes

Downloads

11

Readme

React Class State (react-class-state)

Very small, fast, and unopinionated. You can use just like you want, state-rerenders are minimum especially if you use state.watchState(). Everything is type supported and smooth!


Usage

First, create a React app, then paste this to your console:

npm install react-class-state
//OR
yarn add react-class-state

Creating State

import ClassState from "react-class-state"
import { ITodo } from "./types/ITodo"

class TodoState extends ClassState {
  todos: ITodo[] = []

  // If you want, you can use actions inside the class, if you want you can also follow the next usages
  // Note : Always use arrow functions
  async fetchTodos = () => {
    const response = await fetch("https://jsonplaceholder.typicode.com/todos")
    const data = await response.json()
    this.setState((state) => (state.todos = data))
  }
}
const todoState = new TodoState()
// You can call this in react components, too.
// If you do this process on server or outside of component, you can use this as SSR with NextJS
todoState.fetchTodos()

Creating State as Pure Without Actions

class TodoState extends ClassState { todos: ITodo[] = [] }

const todoState = new TodoState()
const {todos,setTodos} = todoState.getState()

Creating State Easily Without Class (It will create class for you, don't worry)

const todoState = LazyClassState({ todos: ITodo[] = [] })
const {todos,setTodos} = todoState.getState()

API after creating (Usage and examples are both below and in examples folder)

  // Get state outside React
  const {todos, setState, fetchTodos} = todoState.getState()

  // Get state inside React
  const {todos, setState, fetchTodos} = todoState.useState()

  // Set State
  const todo = { text: "I am a todo", completed: false }
  /* First */ todoState.setState({ todos: [todo] /*other state changes*/ })
  /* Second */ todoState.setState((prevState) => ({ todos: [...prevState.todos, todo] /*other state changes*/ }))
  /* Third */ todoState.setState((state) => {
    state.todos.push(todo)
  })

  // Subscribe State
  todoState.subscribeState((currentState,previousState) => {
    console.log("currentState:", currentState)
    console.log("previousState:", previousState)

  // This will re-render only once and whatever you change here will also change the React Component State
  currentState.todos.push(todo)
  })

Usage in React

const App = () => {
  // If you useState, it will cause re-rendering of the React whenever the value changes, so you have to use it.
  const { todos } = todoState.useState()
  return (
    <div>
      {todos.map((todo) => (
        <div key={todo.id}>{todo.title}</div>
      ))}
    </div>
  )
}

You can also get state outside of React.

  const { todos, setState } = todoState.getState()
  setState(/* your code here */)

Changing state inside components

const App = () => {
  const { setState } = todoState.useState()

  useEffect(() => {
    const fetchTodos = async () => {
      const response = await fetch("https://jsonplaceholder.typicode.com/todos")
      setState((state) => (state.todos = await response.json()))
    }
    fetchTodos()
  }, [])

  // Rest of the App
}

Other Ways To Change State

// You can change the state from anywhere, in regular files or inside class components/function components, no matter whether it is async or not,
const response = await fetch("https://jsonplaceholder.typicode.com/todos")
todoState.setState(async (state) => (state.todos = await response.json()))