🎮
FiveM React
  • Welcome
  • Getting Started
    • Installation
  • Hooks
    • useNuiMessage
    • useVisible
    • useNuiData
  • useNuiQuery
  • useNuiMutation
  • Components
    • Visible
    • Link
  • Utils
    • isProduction
    • fetchNui
    • openUrl
    • getResourceName
Powered by GitBook
On this page
  • Overview
  • Usage
  • Importing the Hook
  • Parameters
  • Return Value
  • Example
  • ReactJS
  • LUA
  • How It Works
  • Notes
  • Conclusion
  1. Hooks

useNuiMessage

Overview

The useNuiMessage hook listens for messages sent from the FiveM client-side Lua to the NUI (React) interface. It allows React components to respond to incoming NUI messages.

Usage

Importing the Hook

import { useNuiMessage } from "@yankes/fivem-react/hooks";

Parameters

Parameter
Type
Description

eventName

string

The event name to lister for.

callback

(data?: T) ⇒ void

A function that is called when the message is received/

Return Value

This hook does not return a value but automatically sets up an event listener for NUI messages.

Example

ReactJS

import { useState } from "react";
import { useNuiMessage } from "@yankes/fivem-react/hooks";

type ExampleData = {
    eventName: string;
    message: string;
};

export const MyComponent = () => {
    const [message, setMessage] = useState("");

    useNuiMessage<ExampleData>("nui:example:event", (data: ExampleData) => {
        if (data) {
            setMessage(data.message);
        }
    });

    return (
        <div className="nui-container">
            <h1>NUI Message Listener</h1>
            <p>Received Message: {message}</p>
        </div>
    );
};

LUA

RegisterCommand("send_nui_message", function()
    SendNUIMessage({
        eventName = "nui:example:event",
        message = "Hello from Lua!"
    })
end, false)

How It Works

  1. The React component calls useNuiMessage with an event name (nui:example:event) and a callback function.

  2. When the FiveM client executes the SendNUIMessage function in Lua, the NUI (React) interface receives the event.

  3. The useNuiMessage hook captures the event and executes the callback, updating the React state with the new message.

Notes

  • Ensure that the event name used in SendNUIMessage matches the one in useNuiMessage.

  • The hook properly cleans up the event listener when the component unmounts to prevent memory leaks.

Conclusion

The useNuiMessage hook is essential for handling NUI communication in FiveM React projects. It simplifies listening to and processing messages from Lua, making UI interaction seamless.

PreviousInstallationNextuseVisible

Last updated 2 months ago