Introduction to useState
What is useState?
useState is one of React's built-in hooks that allows function components to have their own state. Think of state as a component's memory - it's data that can change over time and affects what the component displays on screen.
Why Do We Need useState?
Without state, your components would be static and couldn't:
- Respond to user clicks or inputs
- Remember information between renders
- Update what's on screen based on user actions
- Store data fetched from an API
useState Made Simple
Imagine teaching a child to keep track of their toys:
- You give them a notepad with their toys listed (initial state)
- They can look at the notepad anytime to see what toys they have (reading state)
- When they get a new toy, they don't scribble on the notepad - they ask you for a fresh page with the updated list (updating state)
- You give them a completely new list that includes all their toys (re-rendering)
This is exactly how useState works in React!
Basic Syntax
Let's break this down:
- We import the
useState
hook from React - We call
useState(0)
to create a state variable starting with value0
- useState gives us back two things in an array:
- The current state value (
count
) - A function to update that value (
setCount
)
- The current state value (
- When the button is clicked, we call
setCount(count + 1)
to increase the count - React then re-renders our component with the new count value
useState in Real Life
Here's a practical example - a simple task tracker:
Key Rules for useState
-
Always use the setter function to update state, never modify state directly
-
Treat state as immutable - never modify arrays or objects directly
-
State updates may not happen immediately - React might batch them for performance
-
When updating state based on previous state, use the functional form
Common useState Patterns
Toggle State (On/Off)
Form Inputs
Loading States
I apologize for missing the exercises section. Here are three exercises focused on learning useState:
Exercises
Exercise 1: Basic Counter
Objective: Create a counter component with buttons to increase, decrease, and reset the count.
Detailed Instructions:
- Create a new file called
counter.tsx
in your components folder. - Import React and the
useState
hook. - Create and export a functional component named
Counter
. - Inside your component:
- Create a state variable called
count
with an initial value of0
. - Create a
return
statement with adiv
that contains:- An
h2
element to display the current count value - A button labeled "Decrement" that decreases the count by 1 when clicked
- A button labeled "Increment" that increases the count by 1 when clicked
- A button labeled "Reset" that sets the count back to 0 when clicked
- An
- Create a state variable called
- For each button, create an
onClick
handler that uses thesetCount
function to update the state.
Starter Code:
Exercise 2: Toggle Visibility
Objective: Create a component with a button that shows and hides content when clicked.
Detailed Instructions:
- Create a new file called
toggle-content.tsx
in your components folder. - Import React and the
useState
hook. - Create and export a functional component named
ToggleContent
. - Inside your component:
- Create a state variable called
isVisible
with an initial value offalse
. - Create a
return
statement with adiv
that contains:- A button that toggles the
isVisible
state when clicked - Some content (multiple paragraphs) that should only be visible when
isVisible
istrue
- A button that toggles the
- Create a state variable called
- Use conditional rendering to show or hide the content based on the
isVisible
state. - Make the button text dynamic - it should say "Show Content" when content is hidden and "Hide Content" when content is visible.
Starter Code:
Exercise 3: Form with Multiple Fields
Objective: Create a contact form that uses state to manage multiple input fields and form submission.
Detailed Instructions:
- Create a new file called
contact-form.tsx
in your components folder. - Import React and the
useState
hook. - Create and export a functional component named
ContactForm
. - Inside your component:
- Create a state object called
formData
with properties forname
,email
, andmessage
, all initialized as empty strings. - Create another state variable called
submitted
with an initial value offalse
. - Create a function called
handleChange
that updates the appropriate property in theformData
state when any input changes. - Create a function called
handleSubmit
that prevents the default form submission, logs the form data, and setssubmitted
totrue
.
- Create a state object called
- Create conditional rendering to show either:
- The form with input fields for name, email, and message when
submitted
isfalse
. - A success message and a button to submit another message when
submitted
istrue
.
- The form with input fields for name, email, and message when
- Remember to:
- Use the
value
attribute on each input to make it a controlled component. - Connect each input to the
handleChange
function. - Add proper labels for accessibility.
- Include a submit button in the form.
- Use the
Starter Code:
Remember
- Use state only for values that change and affect rendering
- Keep state as simple as possible
- Use one state for each value that can change independently
- When multiple values always change together, group them in an object