Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Megha Ghotkar
Megha Ghotkar

Posted on

Understanding React's useState Hook

React's useState hook is a powerful tool that allows functional components to manage state.
In this brief guide, we'll explore the basics ofuseState with simple examples to help you grasp its usage quickly.
UnderstandinguseState
In React, state represents data that can change over time and affects a component's rendering. Before hooks, class-based components were used for state management. Hooks, includinguseState, simplify state handling in functional components.
Basic Syntax:
The useState hook takes an initial state value and returns an array with two elements: the current state and a function to update that state. Here's how you can use it:
const [state, setState] = useState(initialState);
Example 1: Creating a Counter
Let's create a basic counter component using useState:

import React, { useState } from 'react';function Counter() {  const [count, setCount] = useState(0);  return (    <div>      <p>Count: {count}</p>      <button onClick={() => setCount(count + 1)}>Increment</button>    </div>  );}
Enter fullscreen modeExit fullscreen mode

useState(0) initializes count to 0.
setCount is the updater function for count.
• When the "Increment" button is clicked, it calls setCount to update the state, causing a re-render with the new value.

Example 2: Managing Input Fields
Let's create a component to manage an input field's value:

import React, { useState } from 'react';function InputField() {  const [text, setText] = useState('');  const handleInputChange = (event) => {    setText(event.target.value);  };  return (    <div>      <input        type="text"        value={text}        onChange={handleInputChange}        placeholder="Type something..."      />      <p>You typed: {text}</p>    </div>  );}
Enter fullscreen modeExit fullscreen mode

text manages the input field's value.
setText updates text when the input changes.
• The input value is controlled bytext, and changes are reflected in the paragraph below in real-time.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Location
    Pune,India
  • Education
    BE computer science at MES college Of Engineering
  • Work
    SDE-1 at Elastik Teams
  • Joined

More fromMegha Ghotkar

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp