Lesson 2 - Overview of How State Works in React

State in React

  • What is State?

    • State is a special variable that holds data specific to a component.

    • It's like the internal memory of a component, allowing it to change and react to user interactions or other events.

How State Works

  1. Event Handler: The process starts with an event handler (e.g., a button click, form submission). This event triggers a change in the component's state.

  2. Update State: The component's state is updated using the useState hook. This is where the component's internal data changes.

  3. Re-render: After the state is updated, React re-renders the component. This means that the component's JSX is re-evaluated and the updated state is reflected in the UI.

Key Points Illustrated in the Image

  • The image visually represents the flow of state updates in React.

  • It highlights the role of event handlers in triggering state changes.

  • It emphasizes that React re-renders the component to reflect the updated state, rather than directly manipulating the DOM.

Example using useState

JavaScript

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0); // Initialize state with initial value 0


  return (
    <div>
      <p>Count: {count}</p>
      <button className="btn btn-primary mx-2"  
      onClick={()=>setCount(count+1)}>Increment</button>
      <button className="btn btn-danger mx-2"
       onClick={()=>setCount(count-1)}>Decrement</button>
    </div>
  );
}

export default Counter;

In this example:

  1. The useState hook is used to create the count state variable and a function setCount to update it.

  2. The handleClick function is called when the button is clicked.

  3. Inside handleClick, setCount is called with the updated value of count.

  4. React re-renders the component, displaying the updated count value.

In Summary

State is a fundamental concept in React. By managing and updating state, you can create dynamic and interactive user interfaces that respond to user actions and data changes.

I hope this explanation clarifies how state works in React!

Last updated