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

v1.0.2

Published

🦆 A lightweight Redux kit to manage state in React applications with ease 🦆

Downloads

5

Readme

react-reduckx

Build Status codecov david-dm Greenkeeper badge Minified size License: MIT semantic-release

NPM

🦆 A lightweight Redux kit to manage state in React applications with ease

Installation | Background | Usage | License

Installation

With npm installed, run

npm install react-reduckx

Or with yarn installed, run

yarn add react-reduckx

Peer dependencies

This library uses the following peer dependencies, which will probably already be included in your project while it's using React

To create state selectors, add reselect to your project. It comes with state memoization out of the box.

Background

While developing large-scale React applications, state-management can become messy and hard to follow where data flows. Although there's many good solutions like: redux, react-redux combined with middlewares like redux-thunk and redux-logger and so on, your project can really grow big and will lean too much on 3rd party dependencies. With react-reduckx you get the nescessary bits of these dependencies in one small single toolkit!

Usage

Store

Start by creating a store file in your project. The store initially needs to be feeded with reducer methods and the initial state of the application. Be sure to export the ReduxProvider and the useRedux-hook that the store outputs.

Note: For the sake of showing that one can combine mulitple reducers, the following store file shows how to combine profile and users into a single reducer. We continue the example with only using users.

// store.js
import { combineReducers, createStore } from 'react-reduckx';

import profileReducer from '../ducks/profile/reducers';
import usersReducer from '../ducks/users/reducers';

// Combine multiple reducers with their own state branch
const rootReducer = combineReducers({
    profile: profileReducer,
    users: usersReducer,
});

// Hydrate persisted data or data received from the server
const initialState = {};

// Expose Redux provider and useRedux hook
export const { ReduxProvider, useRedux } = createStore(
    rootReducer,
    initialState
);

Setting up your ducks 🦆🦆

Ducks are your actors of choice in react-reduckx. Let's say, we have a users state branch and we want to fire a user related action in our app and reduce the state when it resolves (or not). As a result we also want to use these state changes in our React components, by using selectors. Toss in a users folder and create the following files:

src
└─── ducks
     └─── users
          │  action-types.js
          │  actions.js
          │  reducers.js
          │  selectors.js

Example ducks

// action-types.js
const PREFIX = 'USERS';

const FETCH_USERS = `${PREFIX}/FETCH_USERS`;

export { FETCH_USERS };
// actions.js
import axios from 'axios';
import { createAsyncAction } from 'react-reduckx';
import { FETCH_USERS } from './action-types';

// Create an async action to fetch users
// This example uses axios to fetch our data, but can be
// any promised-based HTTP client.
const fetchUsers = createAsyncAction(FETCH_USERS, () =>
    axios.get('https://jsonplaceholder.typicode.com/users')
);

export { fetchUsers };
// reducers.js
import { createAsyncActionReducer, createReducer } from 'react-reduckx';
import { FETCH_USERS } from './action-types';

const initialState = {
    isPending: 0,
    items: [],
};

// Define our 'user' state reducer methods, based on action-type.
// createAsyncActionReducer will create async action-types:
// FETCH_USERS_PENDING, FETCH_USERS_SUCCESS, FETCH_USERS_FAIL
// One can add (sub) reducers with: onPending, onSuccess, onFail
const actionsMap = {
    ...createAsyncActionReducer(FETCH_USERS, {
        onSuccess: (state, { payload }) => ({
            items: payload,
        }),
    }),
};

export default createReducer(initialState, actionsMap);

To make selectors work, we only need a tiny library called reselect.

// selectors.js
import { createSelector } from 'reselect';

const branchSelector = state => state.users;

const userListSelector = createSelector(
    branchSelector,
    state => state && state.items
);

export { userListSelector };

UserList

// UsersList.js
// Just output the fetched data from a Higher Order Component (container).
import React from 'react';

function UserList({ data }) {
    return <pre>{JSON.stringify(data, null, 2)}</pre>;
}

export default UserList;

UsersContainer

// UsersContainer.js
import React, { useEffect } from 'react';
import { useRedux } from '../../helpers/store';

import * as UsersActions from '../../ducks/users/actions';
import * as UsersSelectors from '../../ducks/users/selectors';

import UserList from '../../components/UserList';

// Define what we need from our state.
const mapState = state => ({
    userList: UsersSelectors.userListSelector(state),
});

// Describe the actions we want to use
const mapActions = {
    fetchUsers: UsersActions.fetchUsers,
};

export default () => {
    // Use the useRedux hook to map the state props and actions
    const [{ userList }, { fetchUsers }] = useRedux(mapState, mapActions);

    // Fetch the users async
    useEffect(() => {
        fetchUsers();
    }, []);

    return (
        <>
            <UserList data={userList} />
        </>
    );
};

App

Once all is setup, we're good to go and can launch our application! For this we need the ReduxProdiver we exposed from our store, wrap the app's children with it so these will have access to the Redux state context by using the useRedux-hook.

// app.js
import React from 'react';
import ReactDOM from 'react-dom';

import { ReduxProvider } from './store';

import UsersContainer from './containers/Users';

// Create the app by wrapping your components with the Redux provider.
// By doing this all children will have access to the Redux state context.
function App() {
    return (
        <ReduxProvider>
            <UsersContainer />
        </ReduxProvider>
    );
}

ReactDOM.render(<App />, document.getElementById('root'));

License

The react-reduckx package is distributed under the MIT License. Check the LICENSE file for details.