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

use-pipe

v1.1.1

Published

Yet another global state management with React Context and Hooks

Downloads

15

Readme

use-pipe

build npm package code style: prettier

Global state management using React Context and Hooks API.

Sandbox to Counter example

Description

This small helper was built to solve one particluar problem - global state management that can be extended in features, if needed, added better debugging experience, if needed, have reliability of Redux with less boilerplate. And use Hooks of course.

Content

Which problem it solves?

This lib allows easier store creation and usage. Let's take a look at redux example:

You define your action creators and functions that make use of redux-thunk middleware somewhere:

// actions.js
function fetchBooks() {
	// maybe do smth
	return dispatch => {
		// dispatch actions
	};
}

function getBook(id) {
	// maybe do smth
	return dispatch => {
		// dispatch actions
	};
}

Then you create your store and use functions to connect them to the store and component:

// BooksPage.jsx
// import Loader and BooksList
import { Component } from 'react';
import { connect } from 'react-redux';

import { fetchBooks } from './actions'; // import

class BooksPage extends Component {
	componentDidMount() {
		this.props.fetchBooks();
	}

	render() {
		const { isLoading, books = [] } = this.props;

		return isLoading ? <Loader /> : books.map(book => <BookItem key={book.id} book={book} />);
	}
}

const mapStateToProps = state => ({
	books: state.books,
	isLoading: state.loading,
});

const mapDispatchToProps = dispatch => {
	return {
		fetchBooks: () => dispatch(fetchBooks()), // create dispatcher
	};
}; // map

connect(
	mapStateToProps,
	mapDispatchToProps,
)(BooksList); // connect

It just seems like a lot of steps to do. With proposed API, what you do is:

// import Loader and BooksList
import { useBooks } from './books';

const BooksPage = () => {
	const { books, isLoading, fetchBooks } = useBooks((store, { fetchBooks }) => ({
		isLoading: state.loading,
		books: state.books,
		fetchBooks,
	})); // just map

	useEffect(() => {
		fetchBooks({ first: 20 }); // and use
	}, []);

	return isLoading ? <Loader /> : <BooksList />;
};

Global store creation and usage

Knowing that billing pages doesn't have complicated business logic we developed a small ~600b typesafe library for global state management and business logic decoupling. It uses React's Context API and React's Hooks (useContext and useReducer specifically). API was developed to resemble Redux for easier adoption.

Simple steps this helper lib does for you:

  • create context using React.createContext(initialState);
  • create Provider component which uses React.useReducer hook to have the latest state which is passed to created context.Provider;
  • create useStore hook to select needed values/actions from context;

Context creation

To create simple a store you need reducer and actions. Let's start from reducer:

const reducer = {
  setUsers: (state, users) => ({ ...state, users })
  addUser: (state, user) => ({ ...state, users: [...state.users, user]})
};

A reducer is just an object that has key as action type and reducer function as value. Reducer function takes two arguments: current state and passed payload, if any. In example payloads are called users and user. Reducer function should always return a new state. With this structure you don't have to write switch-case and switch and case on action types.

Next, we need a way to change the store:

const actions = {
	fetchUsers: (first = 20) => async (dispatch, state) => {
		const people = await get(`/users?first=${first}`);

		dispatch({ type: 'setUsers', payload: people });
	},
};

Actions might resemble you redux-thunk. For now, we should always dispatch an object with type as action type and, if we need to pass some data to reducer, payload field.

Now we can create store itself:

import { createStore } from 'utils/createStore';

const [UsersContext, UsersProvider, useUsers] = createStore(reducer, actions);

We can also pass initial state:

import { createStore } from 'utils/createStore';

const [UsersContext, UsersProvider, useUsers] = createStore(reducer, actions, {
	users: [],
	isLoading: true,
});

// Recommended to export default context object
export default UsersContext;

createStore returns a tuple of three elements: created context object, context.Provider with value prop bound to the reducer state, and useX hook.

  • context object is needed when you want to define debugging name of context or use it when you need access to the whole state (value);
  • context.Provider should be placed somewhere on top of the tree for its children to have access to state;
  • useX hook can be used to select specific items from the store: hook takes selector function that allows selecting needed items from context.

Context value and usage

Context value is a tuple of [state, actions], where state is the latest state and actions - is a map of passed actions but bound to the state. So if you want to fetch users, you can simply run:

import React, { useContext } from 'react';
import UsersContext from 'context/Users';

const UsersList = () => {
	const [state, actions] = useContext(UsersContext);

	useEffect(() => {
		actions.fetchUsers(10); // first 10, from defined actions on top
	}, []);

	return state.users.map(user => <Usersr key={user.id} user={user} />);
};

You can also use useX hook returned by createStore to select needed values, from the example above we defined its name as useUsers:

import React from 'react';
import { useUsers } from 'context/Users';

const UsersList = () => {
	const [users, fetchUsers] = useUsers((state, actions) => [state.users, actions.fetchUsers]);

	useEffect(() => {
		fetchUsers(10);
	}, []);

	return users.map(user => <User key={user.id} user={user} />);
};

Or when we need only one field:

import React from 'react';
import { useUsers } from 'context/Users';

const Usersr = id => {
	const user = useUsers(state => state.users.find(user => user.id === id));

	// render some info about this Usersr
};

We can await for actions to resolve:

import React, { useState } from 'react';
import { useUsers } from 'context/Users';

const UsersListWrapper = () => {
	const fetchUsers = useUsers((_, actions) => actions.fetchUsers);
	const [isReady, setReady] = useState(false);

	useEffect(() => {
		fetchUsers(10).then(() => setReady(true));
	}, []);

	return isReady && <UsersList />;
};