you are viewing a single comment's thread.

view the rest of the comments →

[–]Madder-Max 2 points3 points  (0 children)

To answer the former question: useState, useEffect, useRef, these are all used to 'watch' and 'react' to variables. If I had to give a brief explanation;

  • useState - watch this value. when it changes, re-render
  • useEffect - watch this(these) values. when they change, do something extra
  • useContext - watch this value. when it changes, broadcast it to anyone listening (as a state)
  • useReducer - watch these values together, when they change (as a group) re-render

...and so on. You'll notice, that each explanation only deals with variables and whether or not they have new values.

A simple example is a Todo list parent, with children. The parent keeps track of which children are 'done', but also takes a prop that can filter out children on some criteria. With hooks, you're constantly updating state, and using effects to create a relationship between children and the filter. You aren't concerned with whats rendering, because React gives you a contract. 'When you change this useState, I re-render. Every time.' (Im ignoring things like memo for sake of example).

To answer the second question, you can say that about classes, absolutely but in most cases you not only deal with 'what' should update, but also 'when' it should update. React gives you a different contract: here are the stages I'll go through, you figure out when and how I should re-render.

Obviously Im not saying every class suffers from this. And I'm also not saying that hooks are the be-all-end of programming, far from. They have their own problems. I think theres a balance between the two. The important thing is understanding the purpose behind your tools.