0
0
NextJSframework~5 mins

State and hooks in client components in NextJS

Choose your learning style9 modes available
Introduction

State lets your component remember things like user input or clicks. Hooks are special tools that help you add state and other features easily.

When you want to remember what a user types in a form.
When you want to show or hide parts of the page after a button click.
When you want to update the page without reloading it.
When you want to keep track of a counter or timer.
When you want to fetch data and show loading or error messages.
Syntax
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.

Examples
This example shows a simple counter that increases when you click the button.
NextJS
'use client';
import { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
}
This example toggles text between ON and OFF when clicked.
NextJS
'use client';
import { useState } from 'react';

export default function Toggle() {
  const [isOn, setIsOn] = useState(false);

  return (
    <button onClick={() => setIsOn(!isOn)}>
      {isOn ? 'ON' : 'OFF'}
    </button>
  );
}
Sample Program

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.

NextJS
'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>
  );
}
OutputSuccess
Important Notes

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.

Summary

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.