diegohaz / diegohaz/constate

Possible to do lazy splitting at time of hook usage?

Open
#108 4 comments 2 reactions 0 assignees View on GitHub
discussion
Dominant language
TypeScript
Stars
4k
Forks
94
Avg merge
27m
Merged PRs (30d)
43

Description

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:
```js
// 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?

```js
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 +;
}

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

function App() {
return (




);
}
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.