cerebral / overmind

Overmind - Frictionless state management
https://overmindjs.org
MIT License
1.58k stars 95 forks source link

Scoped state tracking #479

Open christianalfoni opened 3 years ago

christianalfoni commented 3 years ago

By extending the signature of useAppState we can scope the tracking of state.

const Item = ({ id }) => {
  const item = useAppState(state => state.items[id]) // Tracks ["items.$id"] and any other accessed state on item
}

This is different than doing:

const Item = ({ id }) => {
  const item = useAppState().items[id] // Tracks ["items", "items.$id"] and any other accessed state on item
}

The second example here also tracks the "items" themselves, meaning any added/removed items will cause this component to reconcile. We can currently solve this by passing the whole item down to the component, and do useAppState without using any actual state... this new solution seems more intuitive.

sergeyzwezdin commented 1 year ago

@christianalfoni from example page:

// components/Todos.tsx
import * as React from 'react'
import { useAppState } from '../overmind'
import Todo from './Todo'

const Todos = ({ id }: { id: string }) => {
  const state = useAppState()

  return (
    <ul>
      {Object.keys(state.todos).map(id => <Todo key={id} id={id} />)}
    </ul<
  )
}

export default Todos

// components/Todo.tsx
import * as React from 'react'
import { useAppState } from '../overmind'

const Todo = React.memo(({ id }: { id: string }) => {
  const todo = useAppState(state => state.todos[id])

  return <li>{todo.title}</li>
})

export default Todo

Does it actually work? const todo = useAppState(state => state.todos[id]) returns the whole state object (root state), not specific todo, but Typescript says it's specific todo, not root state.

Overmind version:

    "overmind": "^28.0.2",
    "overmind-react": "^29.0.2",

UPDATE:

Issue is actual for Next.js, while code works on server-side. On a client-side there is no issue.