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-qstate

v0.1.9

Published

QueryHook for managing, caching and syncing asynchronous and remote data in React powered by @tanstack/react-query

Downloads

337

Readme

useQState - A Custom State Management Hook with TanStack Query and SuperJSON

useQState is a custom React hook that simplifies state management by leveraging TanStack Query and SuperJSON. It offers an efficient way to manage both global and local state with automatic serialization of complex data types, all while taking advantage of TanStack Query's powerful caching capabilities.

Features

  • Seamless State Management: Manage state across your React application without additional state management libraries.
  • Automatic Serialization: Effortlessly handle complex data types using SuperJSON.
  • Performance Optimizations: Benefit from TanStack Query's caching and performance features.
  • Intuitive API: Familiar API similar to React's useState hook.

Installation

First, ensure you have React, TanStack Query:

npm install @tanstack/react-query @acoboyz/react-qstate

Setup

Before using useQState, you need to set up the QueryClient and wrap your application with the QueryClientProvider from TanStack Query.

import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient();

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      {/* Your app components go here */}
    </QueryClientProvider>
  );
}

export default App;

Usage

Importing the Hook

import { useQState } from 'path-to-your-useQState-hook';

Basic Example

Copy code
import React from 'react';
import { useQState } from 'path-to-your-useQState-hook';

function Counter() {
  const [count, setCount, resetCount] = useQState<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

useQState automatically serializes and deserializes complex data types like objects and arrays.

import React from 'react';
import { useQState } from 'path-to-your-useQState-hook';

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

function Profile() {
  const [user, setUser, resetUser] = useQState<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] = useQState(['myStateKey'], initialValue);

// To reset the state
resetState();

How It Works

The useQState hook uses TanStack Query to manage stateful data and SuperJSON to serialize and deserialize complex data types. Here's a brief overview:

  • State Initialization: When you first call useQState, it initializes the state with the provided initialData.
  • Data Serialization: If the data is a complex type (object, array, etc.), it gets serialized using SuperJSON.
  • Caching: TanStack Query caches the state data, allowing for efficient updates and retrievals.
  • 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 invalidates the query and 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 TanStack Query's caching to minimize unnecessary re-renders and data fetching.
  • Automatic Serialization: SuperJSON handles serialization of dates, maps, sets, and other complex types out of the box.
  • Simple API: Designed to be as straightforward as React's built-in hooks.

Example: Todo List

import React from 'react';
import { useQState } from 'path-to-your-useQState-hook';

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

function TodoApp() {
  const [todos, setTodos, resetTodos] = useQState<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 { useQState } from 'path-to-your-useQState-hook';

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

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

  React.useEffect(() => {
    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

  • TanStack Query for powerful asynchronous state management.
  • SuperJSON for seamless serialization of complex data types.

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.