DEV Community

Golam_Mostafa
Golam_Mostafa

Posted on • Edited on

useState when to use?

1. Managing simple state:

import React, { useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

2. Managing boolean state:

import React, { useState } from 'react';

function Example() {
  const [isOn, setIsOn] = useState(false);

  return (
    <div>
      <p>The light is {isOn ? 'on' : 'off'}</p>
      <button onClick={() => setIsOn(!isOn)}>
        {isOn ? 'Turn off' : 'Turn on'}
      </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

3. Managing complex state:

import React, { useState } from 'react';

function Example() {
  const [person, setPerson] = useState({ name: '', age: 0 });

  const handleInputChange = event => {
    const { name, value } = event.target;
    setPerson({ ...person, [name]: value });
  };

  return (
    <div>
      <p>Name: {person.name}</p>
      <p>Age: {person.age}</p>
      <input
        type="text"
        name="name"
        value={person.name}
        onChange={handleInputChange}
      />
      <input
        type="number"
        name="age"
        value={person.age}
        onChange={handleInputChange}
      />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

4. Managing array state:

import React, { useState } from 'react';

function Example() {
  const [todos, setTodos] = useState([]);

  const handleAddTodo = () => {
    setTodos([...todos, { id: Date.now(), text: 'New todo' }]);
  };

  return (
    <div>
      <ul>
        {todos.map(todo => (
          <li key={todo.id}>{todo.text}</li>
        ))}
      </ul>
      <button onClick={handleAddTodo}>Add todo</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

5. Updating state based on previous state:

import React, { useState } from 'react';

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

  const handleIncrement = () => {
    setCount(prevCount => prevCount + 1);
  };

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={handleIncrement}>Click me</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

These are just a few examples of the many use cases of the useState hook. The hook is very versatile and can be used to manage any kind of state within a React component.

Top comments (0)