Client Components in the NextJS Framework
Let's now convert our server
component into a client one. To do this,
add the 'use client' directive
at the top of the component file:
'use client';
export default function Test() {
return <h1>hello, user!</h1>;
}
Now we will have access to states
created via useState.
As an example, let's create a state
and display its content in the markup:
'use client';
import { useState } from 'react';
export default function Test() {
let [name, setName] = useState('user');
return <h1>hello, {name}!</h1>;
}
Create a client component with two inputs and a button. Let numbers be entered into the inputs. Upon clicking the button, display the sum of the entered numbers in a paragraph.
Remove the 'use client' directive.
Make sure that in this case NextJS
will throw an error because
states cannot be used
inside server components.