Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I think those rules only apply to useState and useEffect themselves, and not to the setState function you get back when you call useState.


Yes, I think you’re right, there are different restrictions on when useState and setState, though it is worrying seeing confusion straight away about it.

I wonder about a case where there is an expandable panel in a UI, and when expanded it should fetch then display data from a web service. Easy enough to do with this API by splitting the content of the panel out into a second component, but it is going to be very tempting to wrap that useEffect fetch call in an `if (expanded)` condition.

On the other hand, there are lots of positives about this design too, the correctly written code does look very elegant and I can see it solving real problems.


As I understood it you should not opt-in to use state conditionally in your component but you can still conditionally set the state. That means you should not conditionally call `useState` but it is fine to conditionally call the `setState` returned by the `useState`. That is not different to how you would use state in a class based component where you also wouldn't attach a state `this.state = {...}` somewhere in the middle of its lifetime. The component has state from the beginning of its lifetime or it hasn't state at all. There is not such concept as "Now that you are expanded you will transform into a stateful component".


I think the recommended pattern if you need a "conditional effect" would be to just move the `if (expanded)` inside the effect instead of wrapping it.


What is worrying about that useState/setState example? The person just didn't read the page properly, it's not an indictment of the API. Maybe give it a month or two before the claims about confusion, this was just someone skimming the page and missing some details.




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: