Consider this simple client component in Next.js 14+ that uses a button to toggle text visibility.
"use client";
import { useState } from 'react';
export default function ToggleText() {
const [visible, setVisible] = useState(false);
return (
{visible && Hello, Next.js!
}
);
}What will the component display initially and after clicking the button once?
"use client"; import { useState } from 'react'; export default function ToggleText() { const [visible, setVisible] = useState(false); return ( <div> <button onClick={() => setVisible(!visible)} aria-pressed={visible}> Toggle </button> {visible && <p>Hello, Next.js!</p>} </div> ); }
Remember that useState(false) means the text is hidden initially. The button toggles the state.
The component starts with visible = false, so the text is hidden. Clicking the button toggles visible to true, showing the text.
You want to test a client component that uses useState. Which mocking approach is syntactically correct and will not cause errors?
Remember to spread the actual React module to keep other hooks intact and provide a function for useState.
Option A correctly spreads the actual React module and overrides useState with a function returning the desired state tuple. Options A, B, and C either omit spreading or assign useState incorrectly.
Given this test code for a client component using useEffect:
import { render, screen } from '@testing-library/react';
import MyComponent from './MyComponent';
test('renders message', () => {
render( );
expect(screen.getByText('Loaded')).toBeInTheDocument();
});And the component code:
"use client";
import { useState, useEffect } from 'react';
export default function MyComponent() {
const [loaded, setLoaded] = useState(false);
useEffect(() => {
setLoaded(true);
}, []);
return {loaded ? 'Loaded' : 'Loading...'};
}What error will the test produce?
Consider that useEffect runs after render and testing-library queries immediately after render.
The component initially renders 'Loading...'. The useEffect updates state asynchronously. The test queries for 'Loaded' immediately, so it fails to find it.
In a client component, the state is updated as follows:
const [count, setCount] = useState(0); setCount(count + 1); setCount(count + 1); setCount(prev => prev + 1);
What is the final value of count after these updates?
Remember that state updates with the same value of count in closures may batch and overwrite.
The first two setCount calls use the same stale count value (0), so both set count to 1. The last call uses a function updater, incrementing from 1 to 2.
Next.js 14+ introduces server actions callable from client components. When testing client components that invoke server actions, which is true?
Think about where server actions execute and how tests run client components isolated from the server.
Server actions run on the server. When testing client components, these calls must be mocked to prevent errors and simulate server responses.