Skip to content

Possible to do lazy splitting at time of hook usage? #108

@timkindberg

Description

@timkindberg

Hi Diego! Thinking of using this in addition to or instead of zustand. One thing I like about zustand is that you can select from the state when you use the hook, like so:

// If you don't pass anything to the hook it returns everything, and rerenders when anything changes
const foo = useMyStore()

// However, if you pass a selector fn, then it will only "watch" the selected state.
// Good for perf optimizations.
const foo = useMyStore(state => state.foo)

// By default it's a referential equality check, but you can pass different equality fns.
// So you could pass lodash's isEqual to do a deep equal comparison if you needed to.
const someBigObj = useMyStore(state => state.someBigObj, _.isEqual)

Do you think it's possible to accomplish this with constate? Like this?

import React, { useState } from "react";
import createStore from "zustand";

// 1️⃣ Create a custom hook as usual
function useCounter() {
  const [count, setCount] = useState(0);
  const increment = () => setCount(prevCount => prevCount + 1);
  return { count, increment };
}

// 2️⃣ Wrap your hook
const [Provider, useCounterContext] = constate(useCounter)

function Button() {
  // 3️⃣ Use store instead of custom hook, make use of selector api
  const increment = useCounterContext(s => s.increment);
  return <button onClick={increment}>+</button>;
}

function Count() {
  // 4️⃣ Use store in other components
  const count = useCounterContext(s => s.count);
  return <span>{count}</span>;
}

function App() {
  return (
    <Provider>
      <Count />
      <Button />
    </Provider>
  );
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions