DEV Community

govindbisen
govindbisen

Posted on

(3)Hook - 1 . useState

What is useState?

useState is a React Hook that allows functional components to have state.

const [state, setState] = useState(initialState);
Enter fullscreen mode Exit fullscreen mode
  • state → current state value
  • setState → function to update state
  • initialState → initial value

Example: Simple Counter

import React, { useState } from 'react';

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

  const increment = () => setCount(count + 1);
  const decrement = () => setCount(count - 1);

  return (
    <div style={{ textAlign: 'center', marginTop: '50px' }}>
      <h1>Counter: {count}</h1>
      <button onClick={decrement} style={{ marginRight: '10px' }}>-</button>
      <button onClick={increment}>+</button>
    </div>
  );
};

export default Counter;
Enter fullscreen mode Exit fullscreen mode

Explanation

  • count starts at 0.
  • Clicking + increases the counter.
  • Clicking - decreases the counter.
  • setCount updates state and triggers a re-render.

Tips

  • Each useState is independent.
  • Always use the setter function to update state.
  • Functional updates:
setCount(prevCount => prevCount + 1);
Enter fullscreen mode Exit fullscreen mode
  • Functional initialization of state:
const [count, setCount] = useState(() => 0);

homework - learn where to use functional initializtion and update.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)