DEV Community

Nancy Zaky
Nancy Zaky

Posted on

phase/2 FlatIron school React.

Hey everyone,
phase2 has been challenging with all the new concepts but also alot of fun learning about React. Here, I'm going to talk a little about what I learned about useState Hook.

State is a dynamic data that is expected to change in the component, setState will update the state and cause the component to re-render with the updated state value.
for Example, If I have a counter component that increases by 1 on every button click, with React, I could initialize the state value to 0 by calling setState function. with every click, updating the state will cause the whole component to re-render, displaying the new increased value which is now 1 if clicked just once.
This is different from how I used to manipulate the DOM during phase1 using Vanilla JavaScript, I would first find the element that needs to be updated (document.getElementById('id') by the Id/ClassName/TagName then update the inner text/style etc of that element.

Since setState is asynchronous, it doesn't change the state value immediately so in case the new updated state depends on the previous state value it is very important to use callback function with the current state passed in as an argument returning the current state updated.
In the counter example, the new value on click depends on the previous state value, therefore, the callback syntax should be used :
setState((prev) => {
return prev +1
}).
That would be it for my blog, very looking forward to start with phase3, I'll be posting my updates here soon :) .
Here is a link to my React project demo that I finished during phase2 if you would like to check it out:
https://www.youtube.com/watch?v=VEqInyXUWCg&t=199s

Thank you for reading.
Nancy

Top comments (0)