5 ms·
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 peo
by satvikpendem 4y ago
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 https://beta.reactjs.org/learn/you-might-not-need-an-effect
[1] https://twitter.com/dan_abramov/status/1281669881667162112 https://twitter.com/dan_abramov/status/1281669881667162112
- draw_down 4y agoAgreed, 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.
- satvikpendem 4y agoInteresting, 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.
- dragonwriter 4y ago> 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.
- rhaway84773 4y agoA 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 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.
- johnfn 4y agoHuh? 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...)
- onion2k 4y agoThe 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.
- belmont_sup 4y agoFirst 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.
- CottonMcKnight 4y agoSpeaking 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 https://twitter.com/acdlite/status/1581401077915975680
- AgentME 4y agoI'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.
- lmm 4y agoDefine "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.
- BigJono 4y agoIf useEffect isn't for fetching data, what is?
- satvikpendem 4y agoIt can be for fetching data: https://beta.reactjs.org/learn/you-might-not-need-an-effect#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.
- BigJono 4y agoYeah 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.
- clayparade 4y agoI 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.
- shroompasta 4y ago>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
- flippinburgers 4y agouseEffect 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?
- satvikpendem 4y ago> 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.
- acover 4y agoSpecifically a component can mount and unmount at strange times. If you expect use effect to only run once you may run into problems.
- flippinburgers 4y agoYou 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.
- jasonkillian 4y agoAgreed, 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.
- nwienert 4y agoYou 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.
- aidos 4y agoCan 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.
- mynameisvlad 4y agoIsn’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 https://reactjs.org/docs/react-component.html#render
- nwienert 4y agoIt’s recommended now: https://beta.reactjs.org/learn/you-might-not-need-an-effect#adjusting-some-state-when-a-prop-changes https://beta.reactjs.org/learn/you-might-not-need-an-effect#...
- deleted 4y ago[deleted]
- WhiteBlueSkies 4y agoNo, 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.
- cageface 4y agoIf 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.
- andix 4y agoI 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.
- tipiirai 4y ago> 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.
- andix 4y agoEdit: 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.