𝗨𝘀𝗲𝗦𝘁𝗮𝘁𝗲 𝗶𝗻 𝗥𝗲𝗮𝗰𝘁 𝗚𝘂𝗶𝗱𝗲
Your password bar changes from weak to strong as you type. React remembers your typing through state.
State holds data. It tracks what you type or click.
Imagine you type your name.
- Your starting state is an empty string.
- You type J.
- You call a function to update the state from "" to "J".
- You type o.
- You call the function to change the state to "Jo".
Every time you update the state, React re-renders the UI. Re-rendering means React clears the old view and draws a new one with your updated data.
Why not use regular variables? A regular variable changes in your code but does not update the screen. Your users will see old data. React state fixes this by connecting your data to your UI.
How to use useState:
Import it from React. import { useState } from 'react';
Declare it. const [age, setAge] = useState(20);
In this example:
- age is your current value.
- setAge is the function to change the value.
- 20 is your starting value.
Try this now. Open a React project. Create a counter. Click a button to update the count. Watch the screen change instantly.
Source: https://dev.to/kaleablemmadev/usestate-in-react-a-beginners-guide-1j8i