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.