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

@designbycosmic/cosmic-react-state-management

v0.0.3

Published

State management using React context and useReducer

Downloads

3

Readme

App State

This is a redux-like approach to state management using React's Context API and the useReducer hook. Basic understanding of these concepts is helpful.

Inspired by this blog post

State Management with React Hooks and Context API in 10 lines of code!

Basic Idea

We set up a context provider that wraps the entire app. The value of that context provider is the result of the useReducer hook, which includes the current state, plus a dispatch function for updating the state.

How to Use

  1. Set up your initialState and reducer, and pass these to the createAppState function.
// src/state.js

import { createAppState } from "cosmic-react-state-management";

// Redux-like switch statement reducer 
const reducer = (state, action) => {
  switch (action.type) {
    case "changeTheme":
      return {
        ...state,
        color: action.newTheme,
      };
      
    default:
      return state;
  }
};

// An object with the initial app state
const initialState = {
  theme: "light",
};

// After passing the reducer and initial state, `createAppState` returns a
// React Context provider, consumer, and hook for getting/setting the app state
export const { AppStateProvider, AppStateConsumer, useAppState } = createAppState(reducer, initialState);

export default {
  AppStateProvider,
  AppStateConsumer,
  useAppState,
};
  1. Wrap the app in the AppStateProvider. To do this in Gatsby, we have to export a function named wrapRootElement in gatsby-browser.js
// gatsby-browser.js

import React from 'react';
import { AppStateProvider } from "./src/state";

export const wrapRootElement = ({ element }) => {
  return (
    <AppStateProvider>{element}</AppStateProvider>
  );
}
  1. For Functional Components, use the useAppState hook.
// src/components/ThemeChanger.js

import React, { useContext } from "react";
import { useAppState } from "../state";

const ThemeChanger = () => {
  const [{ theme }, dispatch] = useAppState();
  
  const changeTheme = dispatch({
    type: "changeTheme",
    newTheme: theme === "light" ? "dark" : "light",
  });

  return (     
    <Button type="button" onPress={changeTheme}>Change Theme</button> 
  );
};

export default ThemeChanger;
  1. For Class-based Components, use the AppStateConsumer wrapper component.
// src/components/ThemeChangerClass.js

import { AppStateConsumer } from "../state";

class ThemeChangerClass extends React.Component {

  constructor() {
    super();
    this.changeTheme = this.changeTheme.bind(this);
  }

  changeTheme({ theme }, dispatch) {
    dispatch({
      type: "changeTheme",
      newTheme: theme === "light" ? "dark" : "light",
    });
  }

  render() {
    return (
      <AppStateConsumer>
        {([ state, dispatch ]) => {
          return(
            <button 
              type="button"
              onClick={() => this.changeTheme(state, dispatch)}
            >Change Theme</button>
          );
        }}
      </AppStateConsumer>
    );
  }
}

export default ThemeChangerClass;
  1. Optionally define separate reducers for easier code management.
// combine the reducers and initialState into single objects before passing to `createAppState`

const reducer = {
  theme: // theme reducer,
  user: // user reducer, e.g., logged-in status,
  nav: // nav reducer, e.g., mobile nav showing
}

const initialState = {
  theme: // theme initial state,
  user: // user initial state,
  nav: // nav initial state,
}

export const { AppStateProvider, AppStateConsumer, useAppState } = createAppState(reducer, initialState);
  1. Optionally run "middleware" functions before changing state
// src/state.js

import { registerMiddleware } from "cosmic-react-state-management";

registerMiddleware({
  actionType: "changeTheme",
  func: ({ newTheme }) => {
    // track theme changes in Google Analytics
    ga.send("userChangedTheme", newTheme);
  },
});

You'll typically want to call registerMiddleware from wherever you define your reducer.