Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@designbycosmic/cosmic-react-state-management

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@designbycosmic/cosmic-react-state-management

State management using React context and useReducer

  • 0.0.3
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

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.

FAQs

Package last updated on 29 Aug 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc