Skip to content

Commit b1184fd

Browse files
committed
Refactor useRosConnection to utilize useCallback for topic and service handlers, improving performance and preventing unnecessary re-renders.
1 parent a5c19f4 commit b1184fd

1 file changed

Lines changed: 7 additions & 7 deletions

File tree

src/utils/useRosConnection.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useState, useEffect } from 'react';
1+
import { useState, useEffect, useCallback } from 'react';
22

33
// Define the shape of our connection state
44
interface RosConnectionState {
@@ -140,7 +140,7 @@ export function useRosConnection() {
140140
}, []);
141141

142142
// Helper function to create a topic instance
143-
const getTopicHandler = (topicName: string, messageType: string) => {
143+
const getTopicHandler = useCallback((topicName: string, messageType: string) => {
144144
if (!connectionState.ros || !connectionState.connected) {
145145
return null;
146146
}
@@ -150,10 +150,10 @@ export function useRosConnection() {
150150
name: topicName,
151151
messageType: messageType
152152
});
153-
};
153+
}, [connectionState.ros, connectionState.connected]);
154154

155155
// Helper function to create a service instance
156-
const getServiceHandler = (serviceName: string, serviceType: string) => {
156+
const getServiceHandler = useCallback((serviceName: string, serviceType: string) => {
157157
if (!connectionState.ros || !connectionState.connected) {
158158
return null;
159159
}
@@ -163,10 +163,10 @@ export function useRosConnection() {
163163
name: serviceName,
164164
serviceType: serviceType
165165
});
166-
};
166+
}, [connectionState.ros, connectionState.connected]);
167167

168168
// Helper function to create a service server instance
169-
const getServiceServer = (serviceName: string, serviceType: string) => {
169+
const getServiceServer = useCallback((serviceName: string, serviceType: string) => {
170170
if (!connectionState.ros || !connectionState.connected) {
171171
return null;
172172
}
@@ -176,7 +176,7 @@ export function useRosConnection() {
176176
name: serviceName,
177177
serviceType: serviceType
178178
});
179-
};
179+
}, [connectionState.ros, connectionState.connected]);
180180

181181
return {
182182
...connectionState,

0 commit comments

Comments
 (0)