Posts

Showing posts from November, 2022

React Hooks - useState Vs useRef (An explanation)

Image
I have tried to provide a brief  flowchart representation of how useState, useEffect and useRef work. The source for this explanation is from  WebDev Simplified's you tube channel . Suppose you wanted to show a name field and a count field to count how many times you updated the name field.  The diagram below shows the code (not focussing too much on the syntax and stuff), how one would normally do it, and the challenges/details of how react will work in each case. In general, on the left part of the diagram, I have provided the code, the middle part displays the contents of the form as things happen, and have included some explanation on how it all works on the right part.  Hoping the picture is self-explanatory.  The biggest usecase for useRef is to refer to the elements inside of the HTML. Each element inside the focument has a 'ref' attribute which can be set to anything. Most common use is to set focus to a certain element in the DOM. In the pictorial below...