re: Building a chat app with React Hooks, a pragmatic example VIEW POST


Hi Nathan, great tutorial, thanks a lot for sharing it!

I'm learning react and after reading your tutorial have a few doubts.

Wouldn't be this against what react advice related to the use of hooks? Copy paste from the official docs.

  • Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.
  • Only call Hooks from React function components. Don’t call Hooks from regular JavaScript functions. (There is just one other valid place to call Hooks — your own custom Hooks. We’ll learn about them in a moment.)

Sorry I hope you can throw some light! Thanks again!


I am a little bit late for the party but if do not figure it out by now. I will shed some light since the author did not.

When they are saying to call the hooks inside loops, nested functions or conditions does not mean that they are not there for being used in map functions. They are more concerned with the fact of the order of hooks and especially with cases where there is no guarantee that you can preserve the state therefore maintaining the order.

One case is with if statements:

if(!userState) const [user,setUser] = useState('guest'); // order here can not be preserved because it rely upon the userState variable

I do not have a good example about nested functions or for examples but again the order has to be preserved.


Oh pretty cool! This has been wandering my thoughts some time, finally some light indeed! thanks!

code of conduct - report abuse