React State Management and Lifting State Up

Day 2 of learning React Today I explored one of the most important concepts in React State. State is simply data that is tied to your UI. When the state changes, React automatically updates the HTML (UI) to reflect the new data. This is what makes React powerful and dynamic. To manage state, we use useState(). Example: const [count, setCount] = useState(0); count - the current state (data) setCount - the function used to update that state A Bug I Encountered (and what I learned) While learning, I ran into an issue where I updated the state twice in the same function, but the second update overwrote the first. Example of the problem: setCount(count + 1); setCount(count + 1); You might expect the value to increase by 2, but it only increases by 1. Why? State updates in React are asynchronous they don’t happen immediately. React waits until all the code finishes running before applying updates. Solution (Using a variable or functional update) const newCount = count + 1; setCount(newCount); setCount(newCount + 1); New Concepts I Learned Lifting State Up (Definition): This is the process of moving state from a child component to a parent component so that multiple components can share and use the same data. Controlled Input (Definition): A controlled input is an input field whose value is controlled by React state. This means the input value is always in sync with the state. Example: const [value, setValue] = useState(''); <input value={value} onChange={(e) => setValue(e.target.value)} /> React is starting to make more sense now, especially how data flows and updates the UI. It’s not always easy, but each challenge is helping me understand things deeper. Looking forward to Day 3 💪 #React #JavaScript #FrontendDevelopment #WebDevelopment #LearningInPublic #CodingJourney #100DaysOfCode #BuildInPublic

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories