React State and Styling

What is useState?

  • useState is a built-in Hook in React that allows you to manage and update the state of a component.

  • State is essentially data that can change over time within your component.

How does it work?

  1. Import the Hook:

    JavaScript

    import React, { useState } from 'react';
  2. Declare State Variable:

    JavaScript

    const [count, setCount] = useState(0); 
    • count: This is the name of your state variable (you can choose any name).

    • setCount: This is a function that you'll use to update the value of count.

    • 0: This is the initial value of count (you can set it to any value).

  3. Use State Variable and Update Function:

    JavaScript

    <button onClick={() => setCount(count + 1)}>Click me</button>
    <p>You clicked {count} times</p>
    • The onClick handler calls the setCount function to increment the count by 1.

    • The p tag displays the current value of count.

Last updated