useNuiMessage
Last updated
Last updated
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.
import { useNuiMessage } from "@yankes/fivem-react/hooks";
eventName
string
The event name to lister for.
callback
(data?: T) ⇒ void
A function that is called when the message is received/
This hook does not return a value but automatically sets up an event listener for NUI messages.
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>
);
};
RegisterCommand("send_nui_message", function()
SendNUIMessage({
eventName = "nui:example:event",
message = "Hello from Lua!"
})
end, false)
The React component calls useNuiMessage
with an event name (nui:example:event
) and a callback function.
When the FiveM client executes the SendNUIMessage
function in Lua, the NUI (React) interface receives the event.
The useNuiMessage
hook captures the event and executes the callback, updating the React state with the new message.
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.
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.