0
0
NextJSframework~30 mins

State and hooks in client components in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
State and hooks in client components
📖 Scenario: You are building a simple interactive counter on a webpage using Next.js. The counter will let users increase the number by clicking a button.
🎯 Goal: Create a client component in Next.js that uses state and hooks to display a number and a button. When the button is clicked, the number increases by one.
📋 What You'll Learn
Use a client component with the "use client" directive
Create a state variable called count initialized to 0
Add a button that increments count by 1 when clicked
Display the current count value in a <p> tag
💡 Why This Matters
🌍 Real World
Interactive counters are common in web apps for likes, votes, or quantity selectors in shopping carts.
💼 Career
Understanding state and hooks in client components is essential for building dynamic user interfaces in Next.js and React.
Progress0 / 4 steps
1
Create a client component with initial count state
Create a new React functional component called Counter with the "use client" directive at the top. Inside it, use the useState hook to create a state variable called count initialized to 0.
NextJS
Need a hint?

Remember to add "use client" at the top to make this a client component. Use useState(0) to create the count state variable.

2
Add a button to increment the count
Inside the Counter component, add a <button> element. Set its onClick handler to a function that calls setCount(count + 1) to increase the count by one.
NextJS
Need a hint?

Use an arrow function inside onClick to call setCount(count + 1).

3
Display the current count value
Modify the Counter component to display the current count value inside a <p> tag above the button.
NextJS
Need a hint?

Use curly braces inside the <p> tag to show the count value.

4
Export the Counter component as default
Add a default export statement for the Counter component at the end of the file.
NextJS
Need a hint?

Use export default Counter to make this component usable in other files.