0
0
NextJSframework~30 mins

Use client directive in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Client Directive in Next.js
📖 Scenario: You are building a simple Next.js app that shows a button to count clicks. The button needs to update the count on the client side.
🎯 Goal: Create a React component in Next.js that uses the 'use client' directive to enable client-side interactivity with a button that increments a counter.
📋 What You'll Learn
Create a React component file named Counter.jsx.
Add the 'use client' directive at the top of the component file.
Use the useState hook to create a count state variable starting at 0.
Render a button that shows the current count and increments it by 1 when clicked.
💡 Why This Matters
🌍 Real World
Client components in Next.js allow interactive UI elements like buttons, forms, and animations that need to update without refreshing the page.
💼 Career
Understanding the 'use client' directive is essential for Next.js developers to build modern, responsive web apps with React hooks and client-side interactivity.
Progress0 / 4 steps
1
Create the Counter component file
Create a new file named Counter.jsx and add the 'use client' directive as the very first line in the file.
NextJS
Need a hint?

The 'use client' directive must be the first line in the file before any imports or code.

2
Import useState and create count state
In Counter.jsx, import useState from react and create a state variable called count initialized to 0 using useState.
NextJS
Need a hint?

Use const [count, setCount] = useState(0) inside the component function.

3
Render a button showing count and increment on click
In the Counter component, return a <button> element that displays the text Count: {count} and increments count by 1 when clicked using setCount.
NextJS
Need a hint?

Use onClick={() => setCount(count + 1)} on the button element.

4
Use the Counter component in a Next.js page
Create a new file named page.jsx in the same folder and import the Counter component. Then render the <Counter /> component inside the default exported function.
NextJS
Need a hint?

Import Counter and use it inside the page component's return.