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-reducer-with-effects

v1.0.0

Published

React Hook that colocates reducer and side effects

Downloads

27

Readme

use-reducer-with-effects

React Hook that colocates reducer and side effects

NPM JavaScript Style Guide

What it does

It's pretty simple: your reducer can return additional data after it executes to signal it would like to run a side effect.

So instead of:

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 }
    case 'decrement':
      return { count: state.count - 1 }
    default:
      throw new Error()
  }
}

And have your effect logic scattered everywhere in your app, you can write:

function reducerWithEffects(state, action) {
  switch (action.type) {
    case 'increment':
      return { state: {count: state.count + 1}
               log: "Log important information"
               http: {url: "http://server.com", method: "post", params: {count: state.count + 1}, callback: 'after-increment'}}
    case 'after-increment':
      return (action.payload.success) ? { documentTitle: "Success" } { documentTitle: "Error!" }
    case 'decrement':
      return { state: {count: state.count - 1}
               anotherSideEffect: {dataNeededByThatSideEffect: 1} }
    case 'debug':
      return { log: "You can omit the state: key if the state doesn't need to change" }      
    default:
      throw new Error();
  }
}

Where http, log, documentTitle and anotherSideEffect are side effects that (you guessed it right!) call a server, log info, update the page title or do whatever type of side effect you like.

Your reducer is still a pure function: data in and data out. Every side effect key has a data representation of what it needs to do.

Your application uses this hook passing a handlers map. The handlers map knows how to execute the side effects that you returned in your reducerWithEffects.

const handlers = 
{ log: (dispatch, payload) => console.log(payload), 
  documentTitle: (dispatch, payload) => document.title = payload, 
  http: (dispatch, {callback, url, params}) => "...Do an http call and then dispatch({type: callback, payload: result})" }
// etc..  

const initialState = {count: 0}

function App() {
  const [state, dispatch] = useReducerWithEffects(reducerWithEffects, handlers, initialState)
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
}

Check the /example folder for a runnable prototype or visit this sandbox

Why it does

While this is a tiny library in terms of code, it packs a big, opinionated view on how to structure a React application.

If you use this library you probably like to keep all state in one place. And if you like to keep all state in one place you probably like to keep all state transitions in one place (your reducer). If you describe all state transitions in one place then why not taking the extra leap and specify all side effects in one place, so for every user action there is a data representation of what the app is going to do (change the state, call a server, etc.).

Those that use this library tend to:

  • Keep the state all in one place (the top level state)
  • Pass down the dispatch function inside a context
  • Update the relevant bits of the state as the user dispatches actions
  • Pass down all the state via props into the components
  • Every component is a pure/memoized component if possible

While you don't have to do all of the above, this library fits in that philosophy of a simple, clear and maintainable application where components only care about displaying a UI given some props and the reducer controls what's happening in your app.

When it does

When you install it like this:

npm install --save use-reducer-with-effects

License

MIT © frankiesardo

Credit

This hook is created using create-react-hook.

Inspiration for the shape of the returned data is taken from the great citrus library.