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);
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 (
{isDarkMode ? 'Dark Mode' : 'Light Mode'}
Switch to {isDarkMode ? 'Light Mode' : 'Dark Mode'}
);
}
export default ThemeSwitcher;
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);
- Lazy Initialization
For expensive initial states, use a function to initialize state.
const [count, setCount] = useState(() => calculateInitialState());
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.