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

react-hooks-view-model

v0.0.7

Published

A library that makes it easy to model global state changes with reducer-like functions using React Hooks.

Downloads

13

Readme

React Hooks View Model

A lightweight library for modeling global state changes with reducer-like functions using React Hooks.

Motivation

In a sufficiently complex React app one might encounter any number of the following concerns around state management:

  • Async updates to state e.g. fetching data to render from an API
  • Computing values from state often called "selectors" or "derived state"
  • Sharing state across components without tons of props boilerplate
  • Hard to compose and test business logic around state

Often the solution to this problem is introducing Redux, with a number of additional libraries like Redux-Thunk, Reselect, etc. The basic value prop of this set up is that you can now easily write testable/composable pure functions that can easily share the same piece of global state.

However this value prop comes with an opinionated architecture that encourages patterns like writing switch statements which must be careful to return immutable data, decomposing functons across sub-branches of state, the reducer/action creator split, provider components and dispatch, etc. The result of this architecture often leads to unecessary boilerplate and exposing the logic around state changes in unobvious ways.

React Hooks has gone a long way towards making it easy to use all functional patterns for components and local state, but it doesn't provide the benefit Redux does of a simple shared global state and patterns for encouraging writing code in pure functions.

This library providers a few wrapper functions around React Hooks that covers all of the concerns above in a way that encourages pure functions and a simple single global state object.

Example

Define your view model

import {
  define,
  reducer,
  selector
} from 'react-hooks-view-model'

// Intialize state with props from a top-level component
export const initialState = (props) => ({
  loading: false,
  page: 0,
  todos: []
})

// Write easy to test/compose state-in-state-out reducers
export const addTodo = (state, todoStr) => ({
  ...state,
  todos: state.todos.concat({ text: todoStr, completed: false })
})

export const loading = (state) => ({
  ...state,
  loading: true
})

export const doneLoading = (state) => ({
  ...state,
  loading: false
})

// You can also write "async reducers" that remove state update boilerplate
export const fetchTodos = async (state, page = 1) => {
  const todos = await fetch(`/api/todo?page=${page}`)

  // You're always welcome to compose these from other pure reducer functions
  return { ...state, todos: todos.reduce((s, t) => addTodo(s, t), state) }
}

// Write easy to test/compose selectors that return values from derived state
export const completedTodos = (state) =>
  state.todos.filter((todo) => todo.completed)

export const incompleteTodos = (state) =>
  state.todos.filter((todo) => !todo.completed)

// Chain reducers that share the same arguments with state updates inbetween 
export const initTodos = [
  loading,
  fetchTodos,
  doneLoading
]

export default define(initialState, {
  addTodo: reducer(addTodo),
  fetchTodos: reducer(fetchTodos),
  completedTodos: selector(completedTodos),
  incompleteTodos: selector(incompleteTodos),
  initTodos: reducer(initTodos)
})

Initialize the model at the top-level component and wrap with the . Then use the model to call the wrapped functions for state updates.

import { useEffect } from 'react'
import todoModel from './view-model'

const TodoList = () => {
  const { completedTodos, incompleteTodos, Provider } = todoModel.use()

  return <ul>
    {completedTodos().map(todo =>
      <li><strike>{todo}</strike></li>
    )}
    {incompleteTodos().map(todo =>
      <li>{todo}</li>
    )}
  </ul>
}

const Todos = (props) => {
  const {
    addTodo,
    fetchTodos,
    initTodos,
    state
  } = todoModel.use()

  useEffect(initTodos, [])

  return (
    <div>
      {state.loading ? 'Loading...' : <TodoList />}
      <button onClick={() => addTodo('Pick up milk')}>
        Add milk todo
      </button>
      <button onClick={() => fetchTodos(state.page + 1)}>
        Load more
      </button>
    </div>
  )
}

const Main = () => {
  const Provider = todoModel.init(props)
  return <Provider><Todos></Provider>
}