useNuiData
Overview
The useNuiData
hook listens for updates to specific data values sent from the FiveM client-side Lua to the NUI (React) interface. It provides a way to subscribe to data changes associated with a particular key and manage the data within React components.
Usage
Importing the Hook
Parameters
dataId
string
The unique key associated with the data that you want to listen for.
initialValue
T or undefinded
The initial value for the data. If no initial value is provided, it defaults to undefinded
Return Value
The hook returns the current data value corresponding to the specified key
. If no data is received yet, it will return the initialValue
(if provided) or undefined
.
Example
ReactJS
LUA
How It Works
The React component calls
useNuiData
with adataId
(e.g.,"user-profile"
) to subscribe to updates for the specific data associated with that key.When the FiveM client executes the
SendNUIMessage
function in Lua, the NUI (React) interface receives the message and updates the data.The
useNuiData
hook listens for thenui:data:update
event and checks if the received data matches the specifieddataId
.If the
dataId
matches, the hook updates the React state, causing the component to re-render with the new data.
Notes
Ensure that the
dataId
used inSendNUIMessage
matches the one inuseNuiData
.The hook will only update the state for the specified
dataId
, making it easy to manage multiple data streams in a single NUI interface.The hook automatically cleans up the event listener when the component unmounts to prevent memory leaks.
Conclusion
The useNuiData
hook provides a convenient way to manage and subscribe to specific pieces of data in your NUI (React) interface. It simplifies handling updates from Lua and keeps your React components in sync with the game state. This makes it ideal for situations where different parts of your UI depend on various dynamic data sources.
Last updated