Understanding React State

What is State in React?

In React, state refers to an internal data object used by components to remember information between renders.

Why Use State?

How State Works?

  1. State is initialized using the useState hook.
  2. Calling the setter function (e.g., setCount) updates the state.
  3. React re-renders the component with the new state value.

Multiple State Variables

  const [name, setName] = useState('John');
  const [age, setAge] = useState(25);
  

State vs Props

When to Use State?

Rules of State

Complex State (Objects & Arrays)

  const [user, setUser] = useState({ name: 'John', age: 25 });

  // Update name only
  setUser(prev => ({ ...prev, name: 'Jane' }));
  

Important Notes

Conclusion

State is the heart of React components, making them interactive and dynamic. It stores data that changes over time and causes the component to re-render, ensuring the UI reflects the latest values.