Log no. 2 - State, A Component's Memory - Part 2

Log no. 2 - State, A Component's Memory - Part 2

It is a learning day or "Spa Day" today and I am using it to make a big green dent (!) in my React docs reading list. So I am back to reading "State: A component's memory for now." Which explains state at a much deeper level

So bro in a nutshell what have I learned or re-learned:
  • The only argument that `useState` takes is the initial value of your new state variable 
  • For example if you were doing an counter you would start with `useState(0)` (if you wanted to start at zero)
  • every time a component renders, `useState` give you an array containing two values
    • the state variable with the value you stored 
    • the state setter function that can
      • it can update the state variable 
      • more importantly, it can TRIGGER A RE-RENDER
    • THE SYNTAX is something like `const [something, setSomething] = useState(initialValue)`
Okay so that was the first part. So I read some more and made a great big diagram

useState in Action

So I highly doubt anyone can read the diagram but that is not the point here. The point is to write it up. So what do my notes say
  • Your component renders for the first time 
    • Let's say you set an initial state value of `0`
    • Because you passed `0` to `useState` as the initial value, it will return `[0, setValue]`
    • And it returns `[1, setValue]` instead (the values I used for the diagram were a bit different).

An image detailing the final step of the process
    • A giant diagram of useState in action
    • So react remembers that `0` is the latest state value 
  • You update the state
    • When a use clicks a pre-set button, it will call `setValue(value+1)`. Value is `0`, so it's `setValue(1)`.
    • This tells react to remember that `value` is `1` now 
    • And then this TRIGGERS ANOTHER RE-RENDER!!!
  • Your component's second render 
    • React still sees `useState(0)` but it REMEMBERS (!!!) that you have set `value` to `1` - because this is how state works 
    • it is a component's memory 

Comments

Popular posts from this blog

Log no. 1 - State: A Component's Memory , Part 1