8 ms·
A guide to useEffect in React
- miccah 8y agoMaybe I'm not the target audience, but I have no clue what "useEffect" does or why it is important. An introduction on the subject (including which language is being discussed) would be really helpful.
- bzalasky 8y agoIn the JavaScript UI library React, useEffect is a hook (recent addition to the library) that allows you to perform side effects in function components. https://reactjs.org/docs/hooks-effect.html https://reactjs.org/docs/hooks-effect.html
- agrippanux 8y agoReact 16.8 introduced a new concept of hooks, "useEffect" being a built in one. Hooks are extremely useful for streamlining and reusing React component code. "useEffect" in particular can supplant the "componentDidMount" method which among other things is common for fetching data into a component. There are some gotchas to be aware of when using "useEffect" and this article is explaining them.
- uhryks 8y agoThere's a link in the first sentence of the article. It would have taken you less time reading it than it probably took you to write this comment.
- lkbr 8y agoAlso "This article assumes that you’re somewhat familiar with useEffect API." with another link a little further down.
- jameslk 8y agoReact hooks solve a problem most people don't have. Classes worked fine in 99% cases and have the nice benefit of encapsulating any side effects. Hooks make it easy to hide side effects and dependence on state (think global variables) by letting developers hide these things several layers deep in functions that may get called by components. This is a footgun waiting to go off. If you need to use state or side effects, just use classes. Most of the time all you need is pure components with fewer stateful components above controlling the pure components. Pass down your state and state modifiers through explicit and easy to follow props (or use a state management system if you find yourself prop drilling). If you're using state and side effects everywhere, you're probably not using React correctly.
- rajangdavis 8y agoWhen do you actually need to use hooks? I saw a nice visual where hooks ended up reducing code, but I am not sure I grok it.
- snek 8y agoWhen you want to work with state in a component (so most of the time) but are too stubborn to admit FP isn't the right choice for the job
- jameslk 8y agoThis is my feeling too to be honest. I think hooks are very misguided. Unfortunately it's no longer FP anymore when your "referential transparency" has been completely blown away.
- jordanwallwork 8y agoFP?
- jameslk 8y agoFunctional Programming
- jameslk 8y agoI've been using React in projects large and small for years and I can remember VERY FEW situations where I said to myself "gee I wish I could bundle a bunch of state or side effects together and share it between components like React mixins of lore". If you can't think of a situation where you need it, that's probably because you don't. Anything plain old JavaScript class components can't handle here were solved by using HOCs/render prop patterns or React context (often in the form of state management libraries such as Redux).
- deleted 8y ago[deleted]
- ng12 8y ago> While you can useEffect(fn, []), it’s not an exact equivalent. Unlike componentDidMount, it will capture props and state. So even inside the callbacks, you’ll see the initial props and state. In my experience this is a fairly common source of confusion. People have a tendency to write things like: useEffect(() => { const unsub = subscribeToThing(thing => handleThing(props.id, thing)) return () => unsub() }, []) This looks pretty good except it's broken if props.id changes. handleThing() will always be called with the first props.id. I'm the defacto React tutor at my company and issues like this make me pause before recommending new React devs to use hooks. useState is awesome and feels more natural to people than setState(). useEffect seems similarly simple but the subtleties can catch you.
- snek 8y agoI'd be wary to encourage useState. It seems too easy to accidentally use in loops/callbacks/etc where your state would then break because react tracks it via call order instead of call site.
- sophiebits 8y agoThe rule about unconditional calls tends to sound weird (I personally found it very strange when I first saw it), but in my experience, people do not have a hard time following it – it’s very rare to want a variable number of state fields, for example. If you do end up making a mistake, React has both lint rules provided and runtime checks to catch any errors. But from watching many people learn and use Hooks, we haven’t seen it to be a problem in practice.
- littlecranky67 8y agoYou don't use useState to set the state, you use useState() to GET back a function that can mutate the state. And this function is safe to call in a loop or conditional. When using hooks, yes, you have to remember not to call any use* function inside loops or conditionals (or use the linter plugins for that). Besides that, hardly any room for errors.
- sophiebits 8y ago
- bgdam 8y agoHaving used React hooks for the past couple of months, I think I've come to the conclusion that I'm not going to recommend any body to switch away from class components. I understand that hooks solve the problem of being able to compose side-effects and lifecycle in your components, but honestly, in the last three years of using React, I don't think I've ever actually had a scenario where hooks would have been a great solution for me. I'm not sure if this means I've been designing my React components very well, or very badly or what. While hooks look like they might be good at some things (ex: useState is awesome), I think they come with too many subtle gotchas (the amount of literature on handling these gotchas, that's been written in the few months of hooks being in beta is mind-blowing) that I'd much rather just use class components.
- thatswrong0 8y agoWhat gotchas are you referring to besides exhaustively listing dependencies and implementing something like `setInterval` via hooks?
- ryansolid 8y agoThat's ultimately it isn't it. I think Hooks are great and I've been using them and would use them for everything. I'm also a Dev manager, and understanding those gotcha's it isn't even about not knowing which would be an obstacle for less experienced developers, but how easily you repeatedly accidentally fall into them. It's hard. I feel like they are 90% right, but unless you are not only a very competent developer but also insanely careful you will make many mistakes. I perhaps am a bit more torn as I have experience with fine grained libraries like Knockout and MobX and I even more so see the benefit of the potential here. I think the idea of it is a better, more clear way to solve problems (from previous experience). But the number of times I've missed [], or forgot to close over state properly even knowing. I usually catch myself but I can only picture the team biting into this.
- deleted 8y ago[deleted]
- lewisl9029 8y agoI haven't used this pattern very extensively yet myself, so definitely take this with a grain of salt, but I think a good way to avoid the pitfalls around accidentally omitting depencencies consistently might be to define our effect functions as pure functions _outside the scope of the render function_, that takes a list of dependencies from our render function, and then returns an effectful function to pass into useEffect. Since these functions don't even have access to the render function's closure to begin with, we can eliminate the possibility of our effect functions ever lying about their dependencies, as they have no choice but to receive their dependencies explicitly as arguments. Probably easier to demonstrate with a code sample: ``` const effectFn = (dependency1, dependency2) => () => console.log(dependency1, dependency2) const Component = ({prop1, prop2}) => { const dependencies = [prop1, prop2] useEffect(effectFn(...dependencies), dependencies) // rest of render function... } ``` We can even define a separate hook to solidify this pattern and make it less cumbersome to write. I whipped up this quick example a while ago to show coworkers and tentatively named it `useEffectFromArgs`: https://codesandbox.io/s/4wwqnqp3zx https://codesandbox.io/s/4wwqnqp3zx For those who don't want to click the link, it's just a really thin wrapper around useEffect: ``` const useEffectFromArgs = (effectFromArgs, args) => useEffect(effectFromArgs(...args), args) const effectFn = (dependency1, dependency2) => () => console.log(dependency1, dependency2) const Component = ({prop1, prop2}) => { useEffectFromArgs(effectFn, [prop1, prop2]) // rest of render function... } ``` I actually came up with this originally because I wanted a way to be able to test effect functions in isolation as pure functions rather than involve the entire React rendering pipeline just to test something that could have been tested as a pure function, which are by far the simplest tests to write and reason about, and the fastest tests to run. So for me, avoiding the accidental scope capture was really just a nice side effect. The pattern is equally applicable to other hooks like useCallback, which was actually the original motivation for this. I also have another version of this that use named arguments to specify dependencies rather than a list, that I prefer using over the other one because positional semantics don't scale: https://codesandbox.io/s/4x86wy3r60 https://codesandbox.io/s/4x86wy3r60 It does make me wonder why the hooks API doesn't just work like this to begin with though. I could definitely be missing some downsides to this approach, so if anyone wants to chime in with any critiques/insights, I'd love to hear them.
- kaoD 8y agoI've toyed with hooks for a few hours and, even if I understand why they're focusing on teaching the basic pitfalls (dependencies arrays mostly), I don't think they're the most confusing part (as long as you know how closures work, i.e. as long as you know JS). The real deal is `useEffect` vs `useLayoutEffect`. It seems easy, but it's not. When should I use each? According to the docs, use `Layout` if you interact with the DOM for measurement or whatever (I mean, look at its name)... WRONG! I made a custom `useFetch` hook that uses `useEffect` to re-fetch when the URL changes. It should be fine, right? Every other `useFetch` I've seen on GitHub does that too... And it's wrong. I noticed that as soon as I added a second `useFetch` that fetches depending on the first's data, there is flashing in the UI. Since `useEffect` is asynchronous, there's a small gap where both internal states can be desynchronized (completely unrelated to the promise, I mean the internal `isLoading`, etc.) `useLayoutEffect` solves the issue (since it blocks the rendering until both effects are finished updating their internal states) but then... my internal hook implementation affects the external behavior in non-obvious ways! I don't know whether my hook consumer needs to block the UI until all updates finish, so I actually need to make two different `useFetch` and `useSyncFetch` hooks, or just ditch the async one. It's definitely a footgun. I predict this is going to bite everyone's ass. It's also not really well understood (try searching for "useEffect vs useLayoutEffect") and the React team is completely ignoring the issue. I haven't seen it mentioned anywhere, and I can't believe I'm the only one that noticed it (I guess hooks haven't been used that much yet?) The issue is exacerbated by `useEffect` being the "default" in the docs, while `useLayoutEffect` is explained later as an option (even if they admit that it's the safest option if you're migrating from classes). I recommend sticking to `useLayoutEffect` unless you're absolutely 100% sure your consumer does not need to block the UI (when can you be 100% sure?) There's a similar thing with `useState` vs `useRef` for mutable state (where the only difference is that `useState` triggers re-renders) but since `useState` is presented as the default (re-render even if you don't know if for consumer needs to) it does not seem like that much of a footgun (you have to reach for `useRef` if you really need it, e.g. in the infamous `useInterval` Abramov's blog post). It's also very similar to how state vs. instance variables worked, and it's very obvious how `useState` interacts with React (completely different behavior unlike `useLayoutEffect`, which is the same but in different parts of the component lifecycle). When your internal hook implementation affects your component's behavior in non-obvious ways, there's something wrong with the hooks API. As proof, see how many custom `useFetch` hooks use `useLayoutEffect` when they should. Zero. And I'm sure there are many more instances of this problem hidden in other custom hooks (it's hard to tell, since it's not obvious until you use a hook that depends on other hook's output and see the flashing).
- dsenkus 8y agoI rewrote my side project (https://robojs.com https://robojs.com) from Typescript/Redux/React (class based components) to Typescript/Mobx/React (hooks) in less than a week. The process was really simple (mostly deleting code). In the end the source code is so much smaller (at least 50%), simpler, easier to read and reason about, largely because of Mobx, however hooks is so much nicer to work with compared to class components, and I doubt that I would ever want to go back.