DEV Community

Shubha Khadgi
Shubha Khadgi

Posted on • Edited on

Mastering React Hooks as a beginner - useState()

useState – Managing State in React

Think of state like the memory of your app — it remembers what’s happening right now.

For example, imagine you're filling out a form:

You type your name — the app remembers what you typed (that's state).

You check a box — the app knows it’s checked (also state).

You click “Submit” — the app knows the form is being submitted (again, state).

State updates every time something changes in your app, and React uses that info to re-render the screen with the latest changes.

Syntax

const [state, setState] = useState(initialValue);
Enter fullscreen mode Exit fullscreen mode

Toggle Between Light and Dark Mode

You’ve probably seen websites with a button that lets you switch between light and dark themes, right? Let's try to make that.

import React, { useState } from 'react';
import './App.css'; // This is where we define the styles for light and dark modes

function ThemeSwitcher() {
  const [isDarkMode, setIsDarkMode] = useState(false); // Start in light mode (false)

  // Function to toggle between light and dark modes
  const toggleTheme = () => {
    setIsDarkMode(!isDarkMode);  // Toggle the state
  };

  return (
    <div className={isDarkMode ? 'dark-mode' : 'light-mode'}>
      <h1>{isDarkMode ? 'Dark Mode' : 'Light Mode'}</h1>
      <button onClick={toggleTheme}>
        Switch to {isDarkMode ? 'Light Mode' : 'Dark Mode'}
      </button>
    </div>
  );
}

export default ThemeSwitcher;

Enter fullscreen mode Exit fullscreen mode

Tips for better optimization

  • Use Previous State for Updates

If the new state depends on the old state, always pass a function to setState

setCount(prevCount => prevCount + 1);
Enter fullscreen mode Exit fullscreen mode
  • Lazy Initialization

For expensive initial states, use a function to initialize state.

const [count, setCount] = useState(() => calculateInitialState());
Enter fullscreen mode Exit fullscreen mode

Alright, that’s pretty much it for useState. Nothing too crazy, right? You’ve seen how to use it, toggle some themes, and even picked up a few tips for writing cleaner code.

Top comments (0)