Day 1: Mastering React Hooks – Deep Dive into useState
Kshitish Kumar Pothal
Next Js || React js || Frontend Developer || Wix || DSA || 500+ DSA Problem Solved || Java || Python || Kotlin || AWS
Welcome to Day 1 of Mastering React Hooks! Today, we'll explore useState, one of the most fundamental and widely used hooks in React. By the end of this lesson, you'll have a clear understanding of how useState works and how to use it effectively.
UseState: What is it?
A React hook called useState enables you to incorporate state management into functional components. It enables your component to "remember" values between renderings, such as counts or user inputs.
How to Use useState
Here’s a basic example to illustrate its usage:
import React, { useState } from "react";
function Counter() {
// Declare a state variable and a function to update it
const [count, setCount] = useState(0);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Decrement</button>
</div>
);
}
export default Counter;
Explanation:
Common Use Cases for useState
领英推荐
function Toggle() {
const [isVisible, setIsVisible] = useState(false);
return (
<div>
<button onClick={() => setIsVisible(!isVisible)}>
{isVisible ? "Hide" : "Show"} Content
</button>
{isVisible && <p>This is toggled content!</p>}
</div>
);
}
Advanced Tips for useState
setCount((prevCount) => prevCount + 1);
function Form() {
const [name, setName] = useState("");
const [age, setAge] = useState("");
return (
<form>
<input
type="text"
placeholder="Name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<input
type="number"
placeholder="Age"
value={age}
onChange={(e) => setAge(e.target.value)}
/>
<p>
Name: {name}, Age: {age}
</p>
</form>
);
}
const [data, setData] = useState(() => {
return expensiveComputation();
});
Day 1 takeaways:
Stay tuned for Day 2, where we’ll dive into useEffect and learn how to handle side effects in your components! ??
Share your progress or ask questions in the comments!