Skip to content

πŸš€ A powerful & lightweight React hook library that simplifies Redux state management with a familiar useState-like API. Built on Redux Toolkit for optimal performance.

License

Notifications You must be signed in to change notification settings

rajkumar4041/use-redux-state

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

65 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ redux-toolkit-state

npm version License: MIT TypeScript React

A powerful and lightweight React hook library that simplifies Redux state management with a familiar useState-like API. Built on top of Redux Toolkit for optimal performance and developer experience

Documentation/demo | Npm Registry | GitHub Repo

✨ Features

  • 🎯 Simple API: Use redux State with a familiar useState-like interface
  • πŸ”„ Dynamic State Creation: Automatically create and manage Redux slices on-demand
  • 🎨 TypeScript Support: Full TypeScript support with excellent type inference
  • ⚑ Performance Optimized: Built on Redux Toolkit for optimal performance
  • πŸ”§ Flexible Selectors: Advanced state selection capabilities
  • πŸš€ Zero Configuration: Minimal setup required
  • πŸ“¦ Lightweight: Small bundle size with no unnecessary dependencies

πŸ“¦ Installation

npm install redux-toolkit-state

or

yarn add redux-toolkit-state

πŸš€ Quick Start

1. Wrap your app with the provider

import { GlobalReduxProvider } from 'use-toolkit-state';

function App() {
  return (
    <GlobalReduxProvider>
      <YourApp />
    </GlobalReduxProvider>
  );
}

2. Use redux State anywhere in your app

import { useReduxState } from 'use-toolkit-state';

function Counter() {
  const [count, setCount] = useReduxState('counter', 0);

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

πŸ“š API Reference

useReduxState(key, initialValue?)

The main hook for managing redux State. Works just like useState but with global scope.

Parameters:

  • key (string): Unique identifier for the redux State
  • initialValue (optional): Initial value for the state

Returns:

  • value: Current state value
  • setValue: Function to update the entire state
  • update: Function to merge partial updates
  • reset: Function to reset state to initial value
const [value, setValue, { update, reset }] = useReduxState(key, initialValue);

useReduxStateValue(key)

Get the entire value of a redux State without a selector.

const value = useReduxStateValue(key);

useReduxStateSetValue(key, initialValue?)

Provide only Setter [setVal,update]

note : update is for partial update

const [setValue, update] = useReduxStateSetValue(key);

// update (partially)
// setValue (setter)

useReduxStateReset(key)

Provide Reset Handler to reset Particular slice to its initial state

const resetFnc = useReduxStateReset(key);

//call while need
resetFnc();

useReduxStateSelector(key, selector)

Select specific parts of redux State with a selector function.

const selectedValue = useReduxStateSelector(key, (state) => state.someProperty);

useMultipleGlobalStates(keys)

Select multiple redux States at once.

const states = useMultipleGlobalStates(['user', 'settings', 'theme']);

🎯 Examples

Basic Usage

import { useReduxState } from 'use-toolkit-state';

function UserProfile() {
  const [user, setUser] = useReduxState('user', {
    name: 'John Doe',
    email: 'john@example.com',
    age: 30,
  });

  const updateName = (newName: string) => {
    setUser({ ...user, name: newName });
  };

  return (
    <div>
      <h2>{user.name}</h2>
      <p>{user.email}</p>
      <button onClick={() => updateName('Jane Doe')}>Update Name</button>
      {/**`DATA` accessible to the child component **/}
      <ChildComponent />
    </div>
  );
}

const ChildComponent = () => {
  // getter variable with state
  const [userState] = useReduxState('user');

  // without state (value getter)
  const user = useReduxStateValue('user');

  return <div>{user.name}</div>;
};

Using Partial Updates

function Settings() {
  const [settings, setSettings, { update }] = useReduxState('settings', {
    theme: 'light',
    language: 'en',
    notifications: true,
  });

  const toggleTheme = () => {
    update({ theme: settings.theme === 'light' ? 'dark' : 'light' });
  };

  return (
    <div>
      <p>Current theme: {settings.theme}</p>
      <button onClick={toggleTheme}>Toggle Theme</button>
    </div>
  );
}

Advanced State Selection

function UserList() {
  // Select only the users array from the State
  const users = useReduxStateSelector('users', (state) => state.list);

  // Select multiple states
  const { user, settings } = useMultipleGlobalStates(['user', 'settings']);

  return (
    <div>
      <h3>Welcome, {user.name}!</h3>
      <p>Theme: {settings.theme}</p>
      <ul>
        {users.map((user) => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

Shopping Cart Example

function ShoppingCart() {
  const [cart, setCart, { update, reset }] = useReduxState('cart', {
    items: [],
    total: 0,
  });

  const addItem = (item) => {
    const newItems = [...cart.items, item];
    const newTotal = newItems.reduce((sum, item) => sum + item.price, 0);
    update({ items: newItems, total: newTotal });
  };

  const clearCart = () => {
    reset(); // Reset to initial state
  };

  return (
    <div>
      <h3>Shopping Cart ({cart.items.length} items)</h3>
      <p>Total: ${cart.total}</p>
      <button onClick={clearCart}>Clear Cart</button>
    </div>
  );
}

πŸ”§ Advanced Usage

Store Management

import { clearSlices, getRegisteredKeys, getStore } from 'use-toolkit-state';

// Get the store instance
const store = getStore();

// Get all registered state keys
const keys = getRegisteredKeys();

// Clear all slices (useful for testing)
clearSlices();

TypeScript with Custom Types

interface User {
  id: string;
  name: string;
  email: string;
}

interface AppState {
  user: User;
  settings: {
    theme: 'light' | 'dark';
    language: string;
  };
}

function TypedComponent() {
  const [user, setUser] = useReduxState<User>('user', {
    id: '1',
    name: 'John Doe',
    email: 'john@example.com',
  });

  const settings = useReduxStateValue<AppState['settings']>('settings');
}

🀝 Contributing

We welcome contributions from the community! Whether you're fixing bugs, adding features, or improving documentation, your help is appreciated.

How to Contribute

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes following our coding standards
  4. Add tests for new functionality
  5. Commit your changes (git commit -m 'Add amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

Development Setup

# Fork and clone the repository
git clone https://github.com/rajkumar4041/use-redux-state.git
cd use-redux-state

# Install dependencies
npm install

# Start development mode
npm run dev

# Build the project
npm run build

Code Standards

  • Follow TypeScript best practices
  • Add JSDoc comments for public APIs
  • Write meaningful commit messages
  • Include tests for new features
  • Update documentation as needed

For detailed guidelines, see our Contributing Guide.

πŸ› Bug Reports

Found a bug? We'd love to help fix it! Please report bugs using our bug report template.

Before Reporting

  • Check if the issue has already been reported
  • Try the latest version of the package
  • Provide a minimal reproduction example
  • Include your environment details

What to Include

  • Clear description of the bug
  • Steps to reproduce
  • Expected vs actual behavior
  • Code example
  • Environment information (OS, browser, versions)

πŸ”’ Security

We take security seriously. If you discover a security vulnerability, please report it privately.

Reporting Security Issues

Do not create a public GitHub issue for security vulnerabilities.

Instead, please email us at: rajkumarrathod414@gmail.com

What to Include

  • Description of the vulnerability
  • Steps to reproduce
  • Potential impact
  • Suggested fix (if any)

Response Timeline

  • Initial response: Within 48 hours
  • Investigation: Prompt and thorough
  • Fix release: As quickly as possible
  • Public disclosure: Coordinated with reporter

For more details, see our Security Policy.

πŸ“ž Support

Need help? We're here to support you!

Getting Help

  1. πŸ“– Documentation: Check our README and examples
  2. πŸ” Issues: Search existing issues
  1. πŸ“§ Email: Contact us directly at rajkumarrathod414@gmail.com

Common Issues

Installation Problems

# Make sure you're using the correct package name
npm install redux-toolkit-state

# For TypeScript support
npm install --save-dev @types/react @types/react-redux

Runtime Errors

// ❌ Wrong - missing provider
function App() {
  return <YourApp />;
}

// βœ… Correct - with provider
import { GlobalReduxProvider } from 'use-toolkit-state';

function App() {
  return (
    <GlobalReduxProvider>
      <YourApp />
    </GlobalReduxProvider>
  );
}

State Access Issues

// ❌ Wrong - accessing non-existent state
const [user, setUser] = useReduxState('user');

// βœ… Correct - provide initial value
const [user, setUser] = useReduxState('user', { name: '', email: '' });

Support Channels

For detailed support information, see our Support Guide.

πŸ”— Quick Links

πŸ“„ License

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

πŸ™ Acknowledgments

  • Built with Redux Toolkit
  • Inspired by React's useState hook
  • Made with ❀️ for the React community
  • Special thanks to all our contributors and users

Made with ❀️ by Rajkumar Rathod

If you find this library helpful, please consider giving it a ⭐ on GitHub! useReduxState

About

πŸš€ A powerful & lightweight React hook library that simplifies Redux state management with a familiar useState-like API. Built on Redux Toolkit for optimal performance.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •