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

real-simple-context

v1.0.10

Published

Super Simple Context

Downloads

4

Readme

Real Simple Context

  • Quick and easy reducer-based context setup
  • Isolate component updates to specific slices of state with selectors (uses use-context-selection)

Install

yarn add real-simple-context

Table of Contents

  1. Example
  2. createReducerContext
  3. referenceContext param
  4. equalityTest param
  5. Reducer and initialState with vanilla JS
  6. Typescript

Example

CODESANDBOX

context.js (createReducerContext)

import { createReducerContext } from 'real-simple-context';

const initialState = { counter: 0, totalIncrements: 0, totalDecrements: 0 };

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'SET_COUNTER_VALUE': {
      return {
        ...state,
        counter: action.value,
      };
    }
    case 'INCREMENT': {
      return {
        ...state,
        counter: state.counter + 1,
        totalIncrements: state.totalIncrements + 1,
      };
    }
    case 'DECREMENT': {
      return {
        ...state,
        counter: state.counter - 1,
        totalDecrements: state.totalDecrements + 1,
      };
    }
    default: {
      return state;
    }
  }
};

const setCounterValue = (dispatch) => (value) => {
  dispatch({
    type: 'SET_COUNTER_VALUE',
    value,
  });
};

const increment = (dispatch) => () => {
  dispatch({
    type: 'INCREMENT',
  });
};

const decrement = (dispatch) => () => {
  dispatch({
    type: 'DECREMENT',
  });
};

const actions = { setCounterValue, increment, decrement };

export const { Provider, useSelector, useActions } = createReducerContext(
  reducer,
  actions,
  initialState
);

index.js (Provider)

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Provider } from './context';

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

Display.js (useSelector)

import React from 'react';
import { useSelector } from './context';

const Display = ({ stateKey }) => {
  const value = useSelector((state) => state[stateKey]);

  return (
    <div className='display'>
      {stateKey}: {value}
    </div>
  );
};

export default Display;

Buttons.js (useActions)

import React from 'react';
import { useActions } from './context';

const Buttons = () => {
  const { setCounterValue, increment, decrement } = useActions();

  return (
    <div>
      <button type='button' onClick={decrement}>
        Decrement
      </button>
      <button type='button' onClick={increment}>
        Increment
      </button>
      <button
        type='button'
        onClick={() => setCounterValue(Math.floor(Math.random(0, 1) * 100))}
      >
        Randomize
      </button>
    </div>
  );
};

export default Buttons;

App.js

import React from 'react';
import Display from './Display';
import Buttons from './Buttons';
import './App.css';

function App() {
  return (
    <div className='App'>
      <div className='container'>
        <Display stateKey='counter' />
        <Display stateKey='totalIncrements' />
        <Display stateKey='totalDecrements' />
      </div>
      <Buttons />
    </div>
  );
}

export default App;

createReducerContext

| Param | Type | Description | Optional / Required | | ---------------- | -------- | ------------------------------------------------------------------------------------------- | ------------------- | | reducer | Function | Reducer for Context | Required | | actions | Object | Map of actions | Required | | initialState | Object | Initial state for reducer | Required | | referenceContext | Boolean | If true, provides a Context with a reference value (object) docs | Optional | | equalityTest | Function | Function to compare previous and current state docs | Optional |

  • Return Value: Object - { Provider, useSelector, useActions }

Provider

| Param | Type | Description | Optional / Required | | --------- | ------ | -------------------------------------------------------- | ------------------- | | initState | Object | Overwrites initialState set through createReducerContext | Optional |

Example

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Provider } from './context';

ReactDOM.render(
  <Provider initState={{ counter: 5 }}>
    <App />
  </Provider>,
  document.getElementById('root')
);

useSelector

Uses use-context-selection

| Param | Type | Description | Optional / Required | | -------- | -------- | -------------------------------------------- | ------------------- | | selector | Function | Selector function to retrieve slice of state | Required |

  • Return Value: any

Example

const counter = useSelector((state) => state.counter);
const multiple = useSelector((state) => ({
  counter: state.counter,
  totalIncrements: state.totalIncrements,
}));

useActions

  • Return Value: Object

Example

const { increment } = useActions();

// ...

<button onClick={increment}>Increment</button>;

referenceContext param

If true, provides a Context with a reference value (object)

context.js

import {createReducerContext} from 'real-simple-context';

const initialState = { ... };

const reducer = (state = initialState, action) => {
    // .....
}

const actions = { ... };

const { Provider, useSelector, useActions, useReference } = createReducerContext(
    reducer,
    actions,
    initialState,
    true
);

AppComponent.js

import React from 'react';
import { useReference } from './context';

const AppComponent = (props) => {
  const reference = useReference();

  React.useEffect(() => {
    reference.current.AppConfig = props.AppConfig;
  }, []);

  // ....
};

equalityTest param

Function to compare previous and current state

context.js

import isEqual from 'lodash/isEqual';
import {createReducerContext} from 'real-simple-context';

const initialState = { ... };

const reducer = (state = initialState, action) => {
    // .....
}

const actions = { ... };

const { Provider, useSelector, useActions } = createReducerContext(
    reducer,
    actions,
    initialState,
    false,
    isEqual //will do a recursive equality check
);

Reducer and initialState with vanilla JS

When creating the reducer in normal JS, it's important to set the default value of state to initialState:

import {createReducerContext} from 'real-simple-context';

const initialState = { ... };

const reducer = (state = initialState, action) => {
    .....
}

If you don't do this, the property typing won't be correct on the selector state object when using useSelector.

Typescript

real-simple-context exports two types for convenience when setting up a reducer context in typescript: Reducer and DispatchAction

import {createReducerContext, Reducer, DispatchAction} from 'real-simple-context';

const initialState = {...};

const reducer:Reducer<typeof initialState> = (state, action) => {
    ....
}

// ....


const someAction = (dispatch:DispatchAction) => (someString:string) => {
    dispatch({
        type:'SOME_ACTION',
        someString
    })
}

....