ReactJS - use client directive



Directives are similar to detailed instructions. They are necessary when using React Server Components or creating something that works with them, such as a library.

One form of directive is referred to as 'use client.' This indicates which parts of the code execute on the client side, which is similar to our web browser.

Another option is the 'use server.' It defines server-side functions that can be called from client-side code, which runs in our web browser. These directives ensure that everything in React Server Components runs smoothly.

So we are going to discuss ‘use client’ in this tutorial.

What is the use client?

The term 'use client' refers to a particular directive used in React Server Components or when creating something that interacts with them. It helps in figuring out which parts of the code execute on the client side, similar to our web browser.

Usage

To use 'use client,' simply place it at the start of a file, before any other code or imports. Single or double quotations should be used, but no backticks.

import { useState } from 'react';

When should we Use 'use client'?

When dealing with React Server Components, use 'use client' to differentiate between code that runs on the server and code that runs on the client.

Examples

Example − Interactivity and state building

So we will create a simple navigation menu component with two pages: "Home" and "About."

To ensure that it runs on the client side, we will create a NavigationMenu component that uses 'use client'. The component will have navigation buttons for two pages: "Home" and "About." It will display content specific to the selected page based on the user's selection. This will be a straightforward navigation menu that allows users to navigate between different areas of a website.

"use client";
import React, { useState } from "react";
export default function NavigationMenu() {
   const [currentPage, setCurrentPage] = useState("Home");   
   const navigateToHome = () => setCurrentPage("Home");
   const navigateToAbout = () => setCurrentPage("About");   
   return (
      <div>
         <h1>Navigation Menu</h1>
         <ul>
            <li>
               <button onClick={navigateToHome}>Home</button>
            </li>
            <li>
               <button onClick={navigateToAbout}>About</button>
            </li>
         </ul>
         <div>
            {currentPage === "Home" && <p>Welcome to the Home Page!</p>}
            {currentPage === "About" && (
               <p>Learn more about us on the About Page.</p>
            )}
         </div>
      </div>
   );
}

Output

navigation menu

Example − Making Use of Client APIs

Here is another example code which uses the 'use client' directive to create a simple feature that can only run in the browser −

'use client';

import React, { useRef, useLayoutEffect } from 'react';

export default function VideoPlayer() {
   const videoRef = useRef(null);
   
   useLayoutEffect(() => {
      const video = videoRef.current;
      if (video) {
         // Play a video when the component loads
         video.play().catch((error) => {
            console.error('Error playing video: ' + error);
         });
      }
   });
   
   return (
      <video ref={videoRef} controls>
         <source src="your-video.mp4" type="video/mp4" />
         The browser does not support the video tag.
      </video>
   );
}

Output

video app

Example − Using Third-Party Libraries

In our React app, we often use pre-made pieces of code from other people, known as third-party libraries, to help with common tasks or make our app look and work better.

Sometimes, these libraries use specific parts of React. If they do, they need to run on the client side. This is important for libraries that use things like creating context, certain React functions, or need to work with the browser's features.

If a library is updated to work with React Server Components, it will already have the 'use client' marker, meaning it is good to go. But if it has not been updated or if we need to add our own special settings for the library to work, we may need to create a Client Component file between the library and our main code to ensure it runs correctly in a React Server Component. This way, the library can use all the browser's features it needs.

We will show how to use a third-party library in a React project and why we need to create a Client Component file if the library has not been updated for React Server Components −

Assume we want to put a third-party date picker library into our React app. Because this library relies on browser features to show and choose dates, it needs to run on the client side.

Create a client component file called ‘DatePickerClient.js’ and use ‘use client’ directive in it.

'use client';

import React, { useState } from "react";
import DatePicker from "react-datepicker";

export default function DatePickerClient () {
   const [startDate, setStartDate] = useState(new Date());
   return (
      <DatePicker selected={startDate} onChange={(date) => setStartDate(date)} />
   );
};

We will import and use the DatePickerClient component in our main React component called App.js where we want to use the date picker. This allows the third-party date picker library to function properly while using browser features.

import DatePickerClient from './DatePickerClient';

export default function App() {
   return (
      <div>
         <h1>Today's Date is</h1>
         <DatePickerClient />
      </div>
   );
}

Output

today date

The 'DatePickerClient' Client Component works as an intermediary between the third-party date picker library and the React Server Component environment. It ensures that the library can use the browser's date selection features.

Limitations

  • If a file marked with 'use client' is imported from another file that's meant to run on the client, 'use client' doesn't do anything. It only counts when we use it in the main file.

  • If a component file has 'use client,' any time we use that component, it is guaranteed to be a Client Component. However, even without 'use client,' a component can still run on the client side.

  • Whether something is a Client Component or Server Component depends on where it is used. If it is used in a file with 'use client' or in a file linked to one with 'use client,' it's a Client Component. Otherwise, it's a Server Component.

  • 'use client' is not just for components. Any code within the client module will be sent to and run on the client side. It is not limited to components.

  • If a file meant for the server side imports something from a 'use client' file, what it imports must either be a React component or supported data that can be passed to a Client Component. Anything else will cause an error.

Summary

So 'use client' is a useful tool for managing code in React Server Components. It ensures that the correct code is executed on the client side, improving the performance and interactivity of our web applications. Just keep it at the beginning of our file and we can build efficient client-side code for our React applications.

reactjs_reference_api.htm
Advertisements