News for hackers. Stuff that matters.
Re:A Visual Guide to UseEffect by satvikpendem on Monday December 26, 2022 @07:36PM (#34143509)
Lots of people seem to misunderstand useEffect. It's not for transforming local state or for handling user events. In fact, there are many many reasons that people use useEffect for where it's not needed, and the recent React beta docs address this [0]. Their categories include:

- Updating state based on props or state

- Caching expensive calculations

- Resetting all state when a prop changes

- Adjusting some state when a prop changes

- Sharing logic between event handlers

- Sending a POST request

- Chains of computations

- Initializing the application

- Notifying parent components about state changes

- Passing data to the parent

- Subscribing to an external store

- Fetching data

Effects should also be idempotent, they should include pure functions that don't have side effects (such as doing a POST request) which Dan Abramov of the core React team addresses [1].

[0] https://beta.reactjs.org/learn/you-might-not-need-an-effect

[1] https://twitter.com/dan_abramov/status/1281669881667162112

Re:A Visual Guide to UseEffect by draw_down on Monday December 26, 2022 @07:55PM (#34143672)
Agreed, but when you have this many “don’t do what Donny Don’t does”, that may be a smell. I use React a lot and like it, but I do feel that way sometimes. I like that these docs are at least prescriptive and tell you what you should do instead.
Re:A Visual Guide to UseEffect by satvikpendem on Monday December 26, 2022 @08:01PM (#34143718)
Interesting, most of your comments are dead, I just vouched for this one.

Anyway, yeah it might be a code smell if everyone is using them wrong, but I'm not sure how the React team could fix it, at least without breaking changes or moving to some other paradigm.

Re:A Visual Guide to UseEffect by dragonwriter on Monday December 26, 2022 @11:24PM (#34145091)
> Anyway, yeah it might be a code smell if everyone is using them wrong

At least part of the “wrong” use is the recommended best practice has evolved over time, so following the recent recommendations would be “wrong” by the current recommendation.

Re:A Visual Guide to UseEffect by rhaway84773 on Monday December 26, 2022 @07:56PM (#34143676)
A lot of the confusion people have with useEffect is the React team’s dishonest approach to it.

useEffect WAS for side-effects. That’s why it’s named that.

That’s literally the first sentence in the Effects hook page in the current non-Beta documentation.

> The Effect Hook lets you perform side effects in function components:

https://reactjs.org/docs/hooks-effect.html

I completely agree that useEffect should not be used for side effects. The concept of using it to sync with an external system makes far more sense.

But this is a very different and new understanding of what useEffect is. The React team, for whatever reason, does not present it as that. They do not point out that, yes, this was originally supposed to be for effects but they realized that this was a bad idea and have refined how they believe it should be used.

Instead, the documentation and commentary around such changes never point out they are changes and just present them as how things are. Which leads to a tremendous amount of confusion among new developers learning React, because it’s never clear what the actual correct approach is, since you rarely come across commentary in a temporally ordered way.

If the Beta docs included the statement “we used to recommend this for side effects, but now don’t”, any newbie reading that will forever understand why the highly upvoted SO answer from 3 years ago recommends using useEffect for a certain side effect but today, that is probably not the right solution.

Re:A Visual Guide to UseEffect by johnfn on Monday December 26, 2022 @11:32PM (#34145129)
Huh? Syncing with an external system IS a side effect; there's no inconsistency in messaging. React considers everything not part of React to be an external system (document, external store, backend...)
Re:A Visual Guide to UseEffect by onion2k on Tuesday December 27, 2022 @05:18AM (#34147344)
The concept of using it to sync with an external system makes far more sense.

React 18 introduced a new hook called useSyncExternalStore for that, which implies useEffect isn't quite right for that purpose otherwise there'd be no need for a new hook.

Re:A Visual Guide to UseEffect by belmont_sup on Tuesday December 27, 2022 @10:37AM (#34149529)
First time I saw this hook. This seems more like a library implementor’s hook to sync stores from redux, mobx, etc.

You can of course wrap your GET/POST requests to an external network API too but that seems like a lot of unnecessary code to pull in external data.

Re:A Visual Guide to UseEffect by onion2k on Tuesday December 27, 2022 @05:42PM (#34154846)
You never just want to "pull in external data" in a real app though. You need to make the request, deal with injecting auth tokens or headers, handle errors, handle different responses, update global and local state, possibly trigger side effects when the loading starts and ends, do something in a "finally" callback... If your app is non-trivial then you'll almost always end up using a library of some sort. That's where useSyncExternalStore is useful. If you're using useEffect then you're probably not making external requests well.

If you don't need it then you should be questioning whether you even need React, not whether or not you need useEffect.

Re:A Visual Guide to UseEffect by belmont_sup on Wednesday January 04, 2023 @11:08PM (#34255829)
I do agree that better built-in methods should exist that does most of what people have been using useEffect for. Many frameworks come with many tools for specific use cases but react has always left it to the community. If this or new ones are helpful enough, then I’m up to use them. However, your last statement is a bit too presumptuous to assume that not needing useSyncExternalStore means that someone does not need React. I recommend Remix for most apps now if possible, and the number of times anyone needs to use either hooks discussed is very minimal. Remix uses React.

Think your last reply overlaps with the first half of my message. I reach for swr or similar to manage the lifecycle of client side network requests (or any async requests) if necessary. I would imagine that these libraries or new ones adopt useSyncExternalStore internally. If I want to use this hook myself, it seems quite a bit more work to have to write a subscription-based store just to make certain network requests. Many apps aren’t real time either.

Take a single case: analytics. I want it to trigger whenever the page loads (and can’t be done server side for whatever reason). Are you saying that I need the kitchen sink to make this fire-and-forget request? useEffect is fine here. Am I not making an external request well? I just read the useSyncExternalStore RFC. Its primary purpose is to handle external state change in a concurrent environment. Makes sense. Is it to become the default for all “external requests?” Idk. But let’s agree that not all requests require the same care.

Re:A Visual Guide to UseEffect by treis on Tuesday December 27, 2022 @10:58AM (#34149754)
>The concept of using it to sync with an external system makes far more sense.

Why not do that in your setState function?

Re:A Visual Guide to UseEffect by CottonMcKnight on Monday December 26, 2022 @08:01PM (#34143721)
Speaking of badly-named hooks, this tweet infuriated me.

If it's legal, the linter should allow it. F$@k "consistency."

https://twitter.com/acdlite/status/1581401077915975680

Re:A Visual Guide to UseEffect by AgentME on Monday December 26, 2022 @09:26PM (#34144326)
I've run into places where it would be handy to conditionally use hooks, but never the useContext hook, so I can't imagine feeling strongly about that case.
Re:A Visual Guide to UseEffect by lmm on Tuesday December 27, 2022 @01:33AM (#34145836)
Define "legal". Calling glibc memcpy with overlapping arrays worked right up until it didn't. The general contract of react hooks is that they may break in unexpected ways if you call them conditionally. The current implementation of useContext happens to not break.
Re:A Visual Guide to UseEffect by BigJono on Monday December 26, 2022 @08:41PM (#34143988)
If useEffect isn't for fetching data, what is?
Re:A Visual Guide to UseEffect by satvikpendem on Monday December 26, 2022 @08:46PM (#34144019)
It can be for fetching data: https://beta.reactjs.org/learn/you-might-not-need-an-effect#...

However most modern frameworks use something like React Query, GraphQL, etc which handles synchronizing local state with remote data for you.

Re:A Visual Guide to UseEffect by BigJono on Monday December 26, 2022 @09:03PM (#34144146)
Yeah and those modern frameworks use useEffect lol.

This "3rd party library by default" bullshit is killing me. I just read that link, it's basically "here's a general problem with data fetching that every front ender should thoroughly understand OR actually you know what just use a fucking library and forget all about it".

The React docs have been full of this rubbish for a few years now and it's just straight up irresponsible. Worry about what your own library does, and if there's footguns or complexities then explain them thoroughly. Don't just handball them off and treat your API consumers like children.

Re:A Visual Guide to UseEffect by clayparade on Monday December 26, 2022 @11:16PM (#34145045)
I don't really see the issue. The page is just pointing out several anti-patterns with useEffect.

The one talking about fetching data recommends a 3rd party library to make it simple but tells you how to avoid certain issues if you want to go the route of implementing your own fetching.

The POST example talks about how some people will modify a state variable to tell useEffect to send a POST request when you can just do it directly.

Maybe it's not to the depth of your liking but I wouldn't call them rubbish.

Re:A Visual Guide to UseEffect by shroompasta on Monday December 26, 2022 @11:50PM (#34145218)
>The one talking about fetching data recommends a 3rd party library to make it simple but tells you how to avoid certain issues if you want to go the route of implementing your own fetching.

yeah, making it into a custom hook lol.

When did something that was originally worth 5 LOCs turn into 20 LOCs

Re:A Visual Guide to UseEffect by javcasas on Tuesday December 27, 2022 @01:11AM (#34145716)
> When did something that was originally worth 5 LOCs turn into 20 LOCs

When you want it to work properly in all the cases. That includes when new data is being fetched and you don't want to show the old data. Or when you want to not refetch data if the conditions for refetching are not met. Or when you want to cancel an in-progress data fetch if the data shall no longer be shown after fetching it because the user closed the component tasked with showing the data.

I bet your 5 LOC can't do some of these things.

Re:A Visual Guide to UseEffect by shroompasta on Tuesday December 27, 2022 @03:01PM (#34153072)
>That includes when new data is being fetched and you don't want to show the old data

This only really happens when you have race conditions

> Or when you want to not refetch data if the conditions for refetching are not met.

This only happens when you fetch based on state update on the same component

> Or when you want to cancel an in-progress data fetch if the data shall no longer be shown after fetching it because the user closed the component tasked with showing the data.

you can do this with certain conditionals and a cleanup function

over 3 quarters of my data fetching is just a simple fetch on onComponentDidMount

do you mean to tell me I have to bring in a library just for that?

Re:A Visual Guide to UseEffect by javcasas on Tuesday December 27, 2022 @10:35PM (#34157248)
> This only really happens when you have race conditions

Or when the network is unpredictable, you retry because it's taking too long, then the second request succeeds, then somehow the first request succeeds.

> This only happens when you fetch based on state update on the same component

Or on props update.

> you can do this with certain conditionals and a cleanup function

That's no longer 5 LOC.

> over 3 quarters of my data fetching is just a simple fetch on onComponentDidMount

Congratulations. Do you also do that for authenticated requests? If so, either you are using some kind of hardcoded global variable, or you are not using 5 lines of code.

> do you mean to tell me I have to bring in a library just for that?

Of course not. You can implement your own library for that. Or copy-paste it all over the place.

What I'm saying is that for things that are more advanced than basic data fetching, you may want to bring better tools than just fetch + 4 extra LOC.

Re:A Visual Guide to UseEffect by shroompasta on Wednesday December 28, 2022 @11:21AM (#34162505)
>Or when the network is unpredictable, you retry because it's taking too long, then the second request succeeds, then somehow the first request succeeds.

This has an atomically low chance of ever happening, and never happening on single threaded monolithic servers.

>That's no longer 5 LOC.

Okay cool, 7-8 LOC, better than abstracting it into a whole new custom hook.

>Congratulations. Do you also do that for authenticated requests? If so, either you are using some kind of hardcoded global variable, or you are not using 5 lines of code.

You need to be more specific about authenticated requests, because cookies that are sent back as a response will have directions on how they should be sent back to the server on each request that requires no javascript at all.

If you're using token auth with localStorage, which probably isn't a wise idea because you're now susceptible to XSS attacks, then you should already be abstracting that away.

>What I'm saying is that for things that are more advanced than basic data fetching, you may want to bring better tools than just fetch + 4 extra LOC.

here's a pastebin of my wrapper around requests

https://pastebin.com/V33F1f2F

it is already highly configured and abstracted.

All i want to do in the useEffect is await api.getGamesByDate(), and this should be fine.

What you're suggesting is that you support the React team's decision in that I have to have an additional wrapper around my apiCalls just to avoid two fetch calls in Strict Mode.

Does that sound logical to you?

Re:A Visual Guide to UseEffect by javcasas on Friday January 06, 2023 @12:17AM (#34271270)
Congratulations on your code! You created apiCall, effectively your own library for doing requests. The very same thing that you ought to banish.

Once you have setup that library (or hook) yes, using it it's indeed 4 lines of code. That also happens for libraries constructed by others.

Re:A Visual Guide to UseEffect by fexecve on Tuesday December 27, 2022 @12:42AM (#34145512)
> This "3rd party library by default" bullshit is killing me

I've noticed that new developers tend to think of libraries are indivisible units. They never stop to think what React Query uses, it's an atomic unit that you use to do queries, duh.

Re:A Visual Guide to UseEffect by ben0x539 on Tuesday December 27, 2022 @06:09AM (#34147627)
Isn't this like the whole point of abstractions? Sure they don't last forever but still.
Re:A Visual Guide to UseEffect by fexecve on Thursday December 29, 2022 @05:28AM (#34171272)
Well, yes, but new developers need to learn to always delve one layer beneath any abstraction they're using, and understand it. Usually they learn this the hard way by fighting with some abstraction until in a fit of insanity they dig beneath the surface (looking at the library source code or something) and realize that either (a) the docs were lying or (b) the code has a bug or (c) their understanding of what the abstraction was even capable of was wrong.
Re:A Visual Guide to UseEffect by Rapzid on Tuesday December 27, 2022 @06:59AM (#34147917)
Yeah well React's "custom hooks" documentation doesn't help matters.

In reality React doesn't expose public APIs for creating your own useEffect; just the base hooks you can compose into "composite" hooks.

Re:A Visual Guide to UseEffect by darepublic on Tuesday December 27, 2022 @12:02AM (#34145273)
> However most modern frameworks use something like React Query, GraphQL,

imo most projects do not need and are made worse by that bloat.

Re:A Visual Guide to UseEffect by scrollaway on Tuesday December 27, 2022 @04:02AM (#34146842)
I think most react-based projects that need data fetching should absolutely be using SWR (https://swr.vercel.app/).

It's light enough to be worth it from a very small amount of API calls. Having caching and loading states is a significant UX bonus very quickly.

Re:A Visual Guide to UseEffect by andix on Saturday December 31, 2022 @11:38AM (#34198066)
Is it really lighter than react query?
Re:A Visual Guide to UseEffect by flippinburgers on Monday December 26, 2022 @08:55PM (#34144102)
useEffect is precisely for getting/posting data. That is one of its purposes. If the react team is acting suddenly like it isn't they are ignoring... reality?
Re:A Visual Guide to UseEffect by satvikpendem on Monday December 26, 2022 @09:03PM (#34144151)
> useEffect is precisely for getting/posting data. That is one of its purposes.

Where is this said? Because everything I've read has been that doing any non-idempotent action in an effect will cause bugs. Therefore, GETting data is fine but POSTing it is not. I've read this even before these new beta docs.

Re:A Visual Guide to UseEffect by acover on Monday December 26, 2022 @09:07PM (#34144183)
Specifically a component can mount and unmount at strange times. If you expect use effect to only run once you may run into problems.
Re:A Visual Guide to UseEffect by flippinburgers on Thursday January 05, 2023 @01:17AM (#34256704)
You are right. I messaged too quickly. When I think about the times I've used useEffect it has been to GET data for populating a page (as I recall). It has been a little while since I have done frontend hook dev.
Re:A Visual Guide to UseEffect by jasonkillian on Monday December 26, 2022 @09:10PM (#34144202)
Agreed, but it's a pretty big footgun because `useEffect` is often the seemingly easiest way to do the things you list.

I've had similar conversations many times with coworkers before when they were using `useEffect` to keep a state value in sync with a prop. The officially-recommended alternative of manually storing and updating an extra piece of state containing the previous prop value is cumbersome and also had ways it can go wrong. So, since `useEffect` works well enough in most cases and is easier, often the code just sticks with that method. I'm not entirely sure what's really best all tradeoffs considered, but it definitely illustrates how rough edges often pop up in hook-based React.

Re:A Visual Guide to UseEffect by nwienert on Monday December 26, 2022 @10:50PM (#34144878)
You don’t have to store the previous, you can just do an if != right in the render function and call setState there. That’s something I learned from the new beta docs.
Re:A Visual Guide to UseEffect by aidos on Tuesday December 27, 2022 @03:44AM (#34146712)
Can you point to that in the docs? Calling setState during render sounds like a fine way to get infinite loops.

Any of these sorts of hacks tend to be indicative of something not being structured poorly.

Re:A Visual Guide to UseEffect by mynameisvlad on Tuesday December 27, 2022 @04:22AM (#34146989)
Isn’t it also explicitly discouraged with a warning because of how bad it could be?

The React docs are very clear on this:

> The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it’s invoked, and it does not directly interact with the browser.

https://reactjs.org/docs/react-component.html#render

Re:A Visual Guide to UseEffect by nwienert on Tuesday December 27, 2022 @04:50AM (#34147170)
Re:A Visual Guide to UseEffect by aidos on Tuesday December 27, 2022 @08:12AM (#34148296)
Interesting. Thanks for following up.
Re:A Visual Guide to UseEffect by mynameisvlad on Tuesday December 27, 2022 @11:12AM (#34149899)
That’s such a weird 180 on their part considering how explicit they have been about it.

I guess they did a bunch of work to make the case work and are confident about it, but it just seems like such a weird decision considering they’ve been adamantly telling their devs not to do this for years.

Re:A Visual Guide to UseEffect by acemarke on Tuesday December 27, 2022 @12:13PM (#34150815)
Calling `setState` while rendering has been a legitimate thing to do since hooks first came out, but _only_ in one specific scenario / usage pattern.

From the original hooks FAQ at time of release:

- https://reactjs.org/docs/hooks-faq.html#how-do-i-implement-g...

I talked about the reasoning / behavior for this in my React rendering guide:

- https://blog.isquaredsoftware.com/2020/05/blogged-answers-a-...

Re:A Visual Guide to UseEffect by mynameisvlad on Tuesday December 27, 2022 @12:28PM (#34151075)
That still doesn’t change my comment.

It used to explicitly be a thing you must not do for years, it’s weird to go straight 180 on something you actively warn developers not to do. If it wasn’t well documented in the past, then that’s reasonable, but actively spitting out console warnings and explicit documentation warning against it is just going to mean that anyone who isn’t new to react is going to be extremely weary about it.

Re:A Visual Guide to UseEffect by WhiteBlueSkies on Monday December 26, 2022 @10:22PM (#34144636)
No, because the authors didn't know exactly what they were doing. It can't be that secretive. Even rocket science is explained, just put it in the docs and people will learn it.

For 9 years in a row we discuss core concepts of the library like it's some dark art that only select few will ever understand. It's really not that hard.

Re:A Visual Guide to UseEffect by cageface on Tuesday December 27, 2022 @05:57AM (#34147557)
If you have to document 12 wrong ways to use your API that's a sign that it's not well designed.

React was a breath of fresh air when it first arrived and I'm grateful to it for rekindling my interest in front end javascript but the cracks are starting to show. It's just way too hard to write correct, performant React code. I daily see veteran programmers with years of React experience under their belt surprised and confused by the way their React code is behaving.

Re:A Visual Guide to UseEffect by andix on Tuesday December 27, 2022 @06:37AM (#34147809)
I disagree. The awesome thing about react is it’s simplicity. Hooks can be compared to Rxjs from the angular world. That’s really complicated. I’m working with Rx for over 10 years now, and I’m nearly every time overwhelmed. React makes the concept of reactive programming really easy and accessible. But it’s still something complicated, and it will take people time to learn.

Doing those things is not completely wrong, there is just a better/easier solution.

Re:A Visual Guide to UseEffect by tipiirai on Wednesday December 28, 2022 @01:38AM (#34158151)
> If you have to document 12 wrong ways to use your API that's a sign that it's not well designed.

This is so true.

Re:A Visual Guide to UseEffect by andix on Tuesday December 27, 2022 @06:30AM (#34147762)
Edit: okay, the docs show cases where there are no side-effects. For me it’s completely obvious not to use a hook for that…

Aren’t useState and useEffect the two main building blocks for hooks (besides useContext)? Everything is derived from those two.

So I don’t get how it would be wrong to handle any of those things with useEffect. It may not be the most easy to read code, but in the end it’s all useState and useEffect under the hood.