State lets your component remember things like user input or clicks. Hooks are special tools that help you add state and other features easily.
State and hooks in client components in NextJS
'use client'; import { useState } from 'react'; export default function MyComponent() { const [state, setState] = useState(null); return ( <div> {/* UI using state */} </div> ); }
Always add 'use client'; at the top of your file to make it a client component in Next.js.
useState returns an array with the current value and a function to update it.
'use client'; import { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(count + 1)}> Count: {count} </button> ); }
'use client'; import { useState } from 'react'; export default function Toggle() { const [isOn, setIsOn] = useState(false); return ( <button onClick={() => setIsOn(!isOn)}> {isOn ? 'ON' : 'OFF'} </button> ); }
This component lets the user type their name. It remembers what they type and shows a greeting that updates as they type.
It uses useState to keep track of the input value and updates the greeting live.
'use client'; import { useState } from 'react'; export default function NameInput() { const [name, setName] = useState(''); return ( <main style={{ padding: '1rem', fontFamily: 'Arial, sans-serif' }}> <label htmlFor="nameInput">Enter your name:</label><br /> <input id="nameInput" type="text" value={name} onChange={e => setName(e.target.value)} aria-label="Name input" style={{ marginTop: '0.5rem', padding: '0.5rem', fontSize: '1rem' }} /> <p style={{ marginTop: '1rem', fontSize: '1.2rem' }}> Hello, {name || 'stranger'}! </p> </main> ); }
Client components run in the browser and can use hooks like useState.
Always start client components with 'use client'; in Next.js 14+.
Updating state causes the component to re-render and show the latest data.
State lets components remember and update data over time.
Hooks like useState make adding state easy and clean.
Client components in Next.js need 'use client'; to use hooks and state.
Practice
useState in a Next.js client component?Solution
Step 1: Understand what
useStatedoesuseStateis a React hook that allows components to keep track of data that can change, like user input or toggles.Step 2: Identify the purpose in Next.js client components
In Next.js client components,useStatehelps remember and update values without reloading the page.Final Answer:
To store and update data that changes over time within the component -> Option BQuick Check:
State = Remember and update data [OK]
- Thinking useState fetches server data
- Confusing useState with styling or navigation
- Forgetting useState only works in client components
count with initial value 0 in a Next.js client component?Solution
Step 1: Recall the syntax of useState hook
The correct syntax uses array destructuring:const [state, setState] = useState(initialValue);Step 2: Match the syntax with the variable name and initial value
Forcountstarting at 0, it should beconst [count, setCount] = useState(0);Final Answer:
const [count, setCount] = useState(0); -> Option AQuick Check:
useState syntax = [state, setState] [OK]
- Assigning useState directly to a single variable
- Using let instead of const for state
- Not using array destructuring syntax
"use client";
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
setCount(count + 1)}>
Count: {count}
);
}What will be displayed after clicking the button three times?
Solution
Step 1: Understand initial state and button click effect
The initial count is 0. Each click callssetCount(count + 1), increasing count by 1.Step 2: Calculate count after three clicks
After 1 click: count = 1
After 2 clicks: count = 2
After 3 clicks: count = 3Final Answer:
Count: 3 -> Option CQuick Check:
Increment count 3 times = 3 [OK]
- Thinking count resets on each render
- Confusing initial value with updated value
- Ignoring that setCount updates state asynchronously
import { useState } from 'react';
export default function Toggle() {
const [isOn, setIsOn] = useState(false);
return (
setIsOn(!isOn)}>
{isOn ? 'ON' : 'OFF'}
);
}Solution
Step 1: Check for client component requirement
Hooks likeuseStaterequire the component to be a client component, which needs'use client';at the top.Step 2: Verify code for missing directive
The code lacks'use client';at the top, so it will cause an error in Next.js.Final Answer:
Missing 'use client'; directive at the top -> Option DQuick Check:
Client components need 'use client' [OK]
- Forgetting 'use client' directive
- Thinking useState syntax is wrong
- Assuming onClick handler is invalid
Solution
Step 1: Check for 'use client' directive and useState usage
"use client"; import { useState } from 'react'; export default function ShowHide() { const [visible, setVisible] = useState(false); return ( <> setVisible(!visible)}> {visible ? 'Hide' : 'Show'} Message {visible &&Hello, this is the message!
} </> ); } correctly includes'use client';and usesuseStateto track visibility state.Step 2: Verify toggle logic and rendering
The button togglesvisiblestate withsetVisible(!visible), and the message shows only whenvisibleis true.Final Answer:
Option A code snippet correctly implements the toggle behavior -> Option AQuick Check:
Toggle state with useState and 'use client' [OK]
- Not adding 'use client' directive
- Trying to change state variable directly
- Passing current state to setter without toggling
Ready to prove it?
Pass the test and this pattern moves unknown
