TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Two custom React hooks

225 点作者 loh超过 3 年前

23 条评论

mattwad超过 3 年前
Surprised at the negative comments already. I&#x27;m not sure half of the commenters use React on a daily basis. I&#x27;ve re-written these same hooks in various ways, as well as used ones written by others. This look great to me, personally! I&#x27;ve been using a weird implementation of useReducer() (most commonly suggested on SO) but extendState() is a more elegant solution.<p>Couple suggestions:<p>* the repetition of &quot;read&quot; `const [ readRequest, requestRead ] = usePromise(read)` makes it hard for me to keep these things separate. It would be easier if you had a real life example, like &quot;get users&quot; or something but even somethin like `const [ apiState, fetchApiState ] = usePromise( apiRequest )` would be better IMO.<p>* `readRequest.cancel` - sometimes I&#x27;ve wanted to cancel a request but it&#x27;s not an error to show the user, but it looks like the view wouldn&#x27;t be able to tell the difference from a regular http error<p>* `readRequest.reset(`error`)` could be another way to just reset a single property, instead of having to use brackets<p>* uh where is the code for the hooks? A direct link to code or even a library would be great
评论 #29593886 未加载
bayesian_horse超过 3 年前
I think even those examples border on usecases for more complex state management along the lines of redux, Zustand etc. To me, useState with a complex object is an antipattern. I&#x27;d much rather use multiple useState invocations. This eliminates the need for extendState and for handling functions and promises.<p>Also, take a look at Redux Toolkit Query and React Query. Both provide advanced query state management based on hooks.
评论 #29592635 未加载
评论 #29593039 未加载
nightpool超过 3 年前
The initial writing for &quot;useAsyncExtendedState&quot; said &quot;Don&#x27;t use extendState for everything! Use it only when you know you need to merge a partial state.&quot;. However, the example doesn&#x27;t use &quot;setState&quot; at all. This feels like a gap or tension in the API design—if setState doesn&#x27;t get used in practice, why force users to include it? Instead, I think the default react setState pattern is much better, since it allows you to easily set *or* extend your state depending on your usecase:<p><pre><code> const [state, setState] = useState({}); &#x2F;&#x2F; replace setState({foo: 1, bar: 2}); &#x2F;&#x2F; extend setState(currentState =&gt; ({...currentState, foo: 1}));</code></pre>
评论 #29594858 未加载
notpachet超过 3 年前
&gt; In the case of modern front end engineering and React especially, you can reduce everything down to two simple concepts... &gt; Rendering the current state &gt; Updating the state<p>Another day, another React team coming to the belated realization that hooks are an inelegant solution to problems that have already long been solved. Separate your view layer from your application state. Get all those network calls the hell out of there. Relegate your components to simple stream transformers -- props in, HTML out. If you&#x27;re doing anything other than that, your function components aren&#x27;t really pure functions.<p>It&#x27;s frustrating to watch an entire swath of the industry continually rediscover its own inadequacies year after year...
评论 #29593174 未加载
评论 #29595865 未加载
评论 #29594060 未加载
评论 #29594043 未加载
评论 #29595915 未加载
评论 #29592979 未加载
评论 #29593829 未加载
评论 #29597581 未加载
评论 #29594948 未加载
评论 #29595231 未加载
评论 #29593949 未加载
Waterluvian超过 3 年前
I like the `extendState` concept. So far, most of the time, I find that modern JS is fine enough. I can absolutely see the benefit of abstracting this concept. But I&#x27;m always hesitant to layer on top of an API just for little improvements. The cost is deceptively high: you have to re-remember your custom API and others have to learn your custom API.<p><pre><code> setState({...state, foo: &quot;bar&quot;})</code></pre>
评论 #29598074 未加载
null_deref超过 3 年前
Have you thought about using react-query?<p>The second hook is given freely by &#x27;react-query&#x27;, the first one is done little bit differently
tomduncalf超过 3 年前
The extendState one confused me a bit as I just keep one “atom” of state per useState since Hooks were introduced (so you’d end up with foo, setFoo, bar, setBar). I hadn’t really considered doing it the way they are doing it (which feels more like the old this.setState API). How do other people use it?
评论 #29592698 未加载
评论 #29592701 未加载
评论 #29594243 未加载
评论 #29592752 未加载
评论 #29592748 未加载
评论 #29592609 未加载
评论 #29592710 未加载
strogonoff超过 3 年前
A nice approach of separating concerns is having the API layer provide its own, already typed hooks and hook-backed primitives such as `useThing()`&#x2F;`updateThing()` (or `API.thing.useData()`&#x2F;`API.thing.update()`, etc.), which under the hood can do whatever necessary (including using shared logic, API-specific access request handling) while providing common primitives for tracking progress, cancellation[0] and other conveniences. With TypeScript, you can ensure those hooks are typed appropriately and don’t require callers to annotate.<p>Compared to approaches such as `setAsyncState(API.thing.get&lt;ThingState&gt;())`, which do seem clever, the former approach may be a bit more concise, and I’d argue more predictable (if I see a `setState()`, I’d rather not have to do a double take and reason whether or not it actually sets state where it says it would).<p>[0] The cancellation approach in the example in this article rubs me wrong, because the update request is not (and can’t really be) actually cancelled, so the thing may be updated without GUI state knowing.
评论 #29593804 未加载
twic超过 3 年前
Okay so if i have:<p><pre><code> const read = (id: string) =&gt; API.client.get&lt;State&gt;(`things&#x2F;${id}`).then(response =&gt; { return response.data }) const [ readThingRequest, readThing ] = usePromise(read) </code></pre> And i want to read two things from the server:<p><pre><code> const first = readThing(&#x27;alpha&#x27;); const second = readThing(&#x27;beta&#x27;); </code></pre> Then both will update the same readThingRequest, right? So the information in it will vary according to which one returns first or something?<p>This feels like slightly the wrong scoping. Either let me call the wrapped function multiple times, and get multiple metadata objects:<p><pre><code> const [firstRequest, first] = readThing(&#x27;alpha&#x27;); const [secondRequest, second] = readThing(&#x27;beta&#x27;); </code></pre> Or push the wrapping down to the calling of the function:<p><pre><code> const [firstRequest, first] = usePromise(read, &#x27;alpha&#x27;); const [secondRequest, second] = usePromise(read, &#x27;beta&#x27;);</code></pre>
评论 #29601054 未加载
enjoylife超过 3 年前
I don&#x27;t know what applications they are developing but an application only needing two custom two hooks, would be a quite trivial one. Not to mention the hook in the article extendState is basically bringing back the Component `this.setState` semantics but not much else.
评论 #29592776 未加载
Waterluvian超过 3 年前
Pedantic nit: [ readRequest, requestRead ] reminds me of one of my least favourite nitfalls from Django: FileField and FieldFile. Yes, the names make sense. But human brains mash these things up so regularly that I never seem to be able to permanently remember what&#x27;s what. I&#x27;m always triping on them.<p>This also brings me to something I&#x27;ve been wrestling with a bit: Array unpacking allows you to pick your own variable names, but you also generally have to unpack everything if you want some later variables. Order matters. I find this is not very self-documenting and is less fun for autocomplete.<p>Object unpacking lets you pick and choose what pieces you need from the hook&#x27;s interface, and they come pre-named, which is good but sometimes bad.<p>I think I&#x27;m settling on Object unpacking being the better pattern for my tastes.
评论 #29604210 未加载
tuan超过 3 年前
In the design pattern mentioned at the end, there are some application state that are stored in both `updateRequest` and `state`, i.e. the data that is returned from the update response (stored in updateRequest) and is used to extend `state`. Having the same data stored in 2 different states seems error-prone. Which one is the source of truth when the 2 states accidentally get out of sync ? For example, nothing prevents extendState() to be called again to modify the `state` to something that is not the same as the value from update response.
评论 #29594987 未加载
thrwy_918超过 3 年前
Something I often want to do is write a custom hook with internal state that will be used by two or three components - and what I really want to do is have <i>consistent internal state</i> for that hook, regardless of which component its being invoked from.<p>This obviously doesn&#x27;t work with vanilla hooks, but is there a way to achieve this pattern? It seems like it would be so light and fast compared to a heavier solution
评论 #29595109 未加载
评论 #29595157 未加载
评论 #29595114 未加载
评论 #29595135 未加载
brundolf超过 3 年前
I think everyone has their own implementation of usePromise; it’s weird to me that it isn’t included out of the box
imbnwa超过 3 年前
Could Hooks be construed as Facebook Engineering&#x27;s attempt at modeling React as an Effect monad?
knuthsat超过 3 年前
Hooks are great!<p>Although, when I see code snippets on the internet I always wonder how do people test this.<p>The fact that dependencies are declared as imports and all the logic is inside the component function, it feels like you have to shuffle things around just to make the thing runnable outside of React.
评论 #29593363 未加载
评论 #29592862 未加载
评论 #29592440 未加载
评论 #29592672 未加载
评论 #29592362 未加载
DangitBobby超过 3 年前
I have a custom hook that I like to use called useLocalStorage which is just a wrapper around useState which first looks for existing state in localStorage. There is a defaultState argument if there&#x27;s nothing in localStorage.
emadabdulrahim超过 3 年前
Thanks for sharing your post. I want to highlight that react-query solves all of those problems very elegantly. You should check it out if you haven&#x27;t already.
culi超过 3 年前
<a href="https:&#x2F;&#x2F;usehooks.com&#x2F;" rel="nofollow">https:&#x2F;&#x2F;usehooks.com&#x2F;</a>
andrewstuart超过 3 年前
How is extendState different to setState?<p>setState already allows you to extend the current state.<p>I don&#x27;t get it.
评论 #29598290 未加载
lifeplusplus超过 3 年前
simple few concise meaningful lifecycles methods to vague handicapped overlapping infinite hooks, really outdone in the name of progress.
TimMeade超过 3 年前
Excellent! Love the extended state.
评论 #29592467 未加载
flippinburgers超过 3 年前
Just use redux.