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

@acoboyz/react-zstate

v0.3.0

Published

StateHook for managing, caching and syncing asynchronous and remote data in React powered by zustand

Downloads

290

Readme

useZState - A Custom State Management Hook with Zustand

useZState is a custom React hook that simplifies state management by leveraging Zustand. It offers an efficient way to manage both global and local state with minimal boilerplate and excellent performance, thanks to Zustand’s lightweight and flexible API.

Features

  • Efficient Global State Management: Share state across your React application without the overhead of Context or Redux.
  • Performance Optimizations: Benefit from Zustand’s selective re-rendering and subscription mechanisms.
  • Simple API: An intuitive API similar to React’s useState hook.
  • No Serialization Overhead: Direct state management without the need for serialization libraries.

Installation

npm install @acoboyz/react-zstate

Setup

No additional setup is required beyond installing Zustand. You can start using useZState in your components.

Usage

Importing the Hook

import { useZState } from '@acoboyz/react-zstate';

Basic Example

import React from 'react';
import { useZState } from '@acoboyz/react-zstate';

function Counter() {
  const [count, setCount, resetCount] = useZState<number>('counter', 0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(prev => prev + 1)}>Increment</button>
      <button onClick={resetCount}>Reset</button>
    </div>
  );
}

Managing Complex Data Types

useZState can handle complex data types like objects and arrays effortlessly.

import React from 'react';
import { useZState } from '@acoboyz/react-zstate';

interface UserProfile {
  id: number;
  name: string;
  email: string;
}

function Profile() {
  const [user, setUser, resetUser] = useZState<UserProfile | null>('userProfile', null);

  const updateEmail = (email: string) => {
    setUser(prevUser => (prevUser ? { ...prevUser, email } : null));
  };

  return (
    <div>
      {user ? (
        <>
          <h1>{user.name}</h1>
          <p>{user.email}</p>
          <button onClick={() => updateEmail('[email protected]')}>Update Email</button>
        </>
      ) : (
        <p>No user data available.</p>
      )}
      <button onClick={resetUser}>Reset Profile</button>
    </div>
  );
}

Resetting State

You can reset the state to its initial value using the resetState function.

const [state, setState, resetState] = useZState(['myStateKey'], initialValue);

// To reset the state
resetState();

How It Works

The useZState hook uses Zustand to manage stateful data efficiently. Here’s a brief overview:

  • State Initialization: When you first call useZState, it initializes the state with the provided initialData for the given key.
  • State Management: Zustand stores the state in a global store, allowing for shared state across components.
  • Selective Re-rendering: Components that use useZState only re-render when the specific state slice they depend on changes.
  • State Updates: Use the setState function to update the state. It supports both direct updates and updater functions (like React's setState).
  • State Reset: The resetState function resets the state to its initial value.

Benefits

  • Global State Without Additional Libraries: Manage global state without needing Redux or Context API.
  • Performance Optimizations: Leverage Zustand’s efficient state management to minimize unnecessary re-renders.
  • Simple API: Designed to be as straightforward as React’s built-in hooks.
  • No Serialization Overhead: Direct state management without the need for serialization libraries.

Example: Todo List

import React from 'react';
import { useZState } from '@acoboyz/react-zstate';

interface Todo {
  id: number;
  text: string;
  completed: boolean;
}

function TodoApp() {
  const [todos, setTodos, resetTodos] = useZState<Todo[]>('todos', []);

  const addTodo = (text: string) => {
    setTodos(prevTodos => [...prevTodos, { id: Date.now(), text, completed: false }]);
  };

  const toggleTodo = (id: number) => {
    setTodos(prevTodos =>
      prevTodos.map(todo =>
        todo.id === id ? { ...todo, completed: !todo.completed } : todo
      )
    );
  };

  return (
    <div>
      <button onClick={() => addTodo('New Task')}>Add Todo</button>
      <button onClick={resetTodos}>Reset Todos</button>
      <ul>
        {todos?.map(todo => (
          <li key={todo.id}>
            <span
              onClick={() => toggleTodo(todo.id)}
              style={{ textDecoration: todo.completed ? 'line-through' : undefined }}
            >
              {todo.text}
            </span>
          </li>
        ))}
      </ul>
    </div>
  );
}

Advanced Usage

Using with Local Storage

If you want to persist state across browser sessions, you can integrate localStorage:

import { useZState } from '@acoboyz/react-zstate';
import { useEffect } from 'react';

function usePersistentState<T>(key: string, initialData: T) {
  const [state, setState, resetState] = useZState<T>(key, initialData);

  useEffect(() => {
    const storedData = localStorage.getItem(key);
    if (storedData) {
      setState(JSON.parse(storedData));
    }
  }, [key, setState]);

  useEffect(() => {
    if (state !== undefined) {
      localStorage.setItem(key, JSON.stringify(state));
    }
  }, [key, state]);

  return [state, setState, resetState] as const;
}

Contributing

Contributions are welcome! Feel free to open issues or submit pull requests on the GitHub repository.

License

This project is licensed under the MIT License.

Acknowledgments

  • Zustand for its lightweight and flexible state management.

By providing this hook, we aim to simplify state management in React applications, making it more efficient and developer-friendly. If you have any questions or need further assistance, please don’t hesitate to reach out.