Chapter 14 HOOKS | useState(0)
granthcodes.com

Chapter 14 HOOKS | useState(0)

In the world of React, hooks have become an essential part of functional components, allowing us to manage state and side effects efficiently. One of the most fundamental hooks that every React developer starts with is useState.

1. useState

The useState hook is used to add state to functional components. Before hooks, managing state was only possible in class-based components. With useState, this limitation is gone!

Here’s a quick breakdown:

- useState returns an array with two elements:

- The current state value.

- A function that allows you to update this state.

Let’s look at an example to understand this better:

import React, { useState } from 'react';

function Counter() {

  // Declare a new state variable, "count"

  const [count, setCount] = useState(0);

  return (

    <div>

      <p>You clicked {count} times</p>

      <button onClick={() => setCount(count + 1)}>

        Click me

      </button>

    </div>

  );

}        



How does it work?

- The useState(0) initializes the state variable count to 0.

- Each time the button is clicked, setCount updates the count variable, causing the component to re-render with the new state value.

In a functional component, where you can't use this.state like in class components, useState provides a simple, declarative way to manage state. It's perfect for managing local component states such as form inputs, counters, toggles, and more.

Why is useState so important?

- Simplified state management: You no longer need to worry about classes, constructors, or this.setState.

- Separation of concerns: Hooks allow you to manage state, side effects, and context in a cleaner, more modular way.

This is just the beginning of what React hooks can offer! Stay tuned for more chapters where we dive deeper into other hooks like useEffect, useContext, and more.


要查看或添加评论,请登录

Himanshu Verma的更多文章

社区洞察

其他会员也浏览了