I was learning a bit about using 'useRef' hooks in React Native functions. While examining some code I found on the Internet...I saw usage including question marks ("?"), like this (as noted in the code):
import React, { useEffect, useRef, useState } from 'react';
import {
Button,
Dimensions,
StyleSheet,
View,
} from 'react-native';
import { SignalingChannel } from './SignalingChannel';
import { mediaDevices, MediaStream, RTCPeerConnection, RTCView } from "react-native-webrtc";
import { config } from './config';
const STREAM_ID = "170714163152216487974907";
export const Publisher = () => {
//...
const peerConnection = useRef<RTCPeerConnection>()
peerConnection.current = new RTCPeerConnection({
iceServers: []
})
peerConnection.current?.addStream(localStreamRef.current); //WHY THE "?" AFTER 'peerConnection.current'...?
peerConnection.current.onsignalingstatechange = () => console.log(peerConnection.current?.signalingState) //WHY THE "?" AFTER 'peerConnection.current'...?
peerConnection.current.onicecandidateerror = console.log
peerConnection.current.onicecandidate = (event) => {
const candidate = event.candidate;
if (candidate && signalingChannel.current?.isChannelOpen()) { //WHY THE "?" AFTER 'signalingChannel.current'...?
signalingChannel.current?.sendJSON({ //WHY THE "?" AFTER 'signalingChannel.current'...?
command: "takeCandidate",
streamId: STREAM_ID,
label: candidate.sdpMLineIndex.toString(),
id: candidate.sdpMid,
candidate: candidate.candidate,
})
}
}
const offer = await peerConnection.current.createOffer();
await peerConnection.current.setLocalDescription(offer);
//...
};
I have attempted to find information about what these question marks are used for without any success. It also seems that 'useRef' accepts extensions such as those in the above code, like "peerConnection.current.createOffer();" or "signalingChannel.current?.isChannelOpen()"...which also was not mentioned in the documentation I was using about the 'useRef' hook. Any information about these characters and usage is appreciated.
CodePudding user response:
it's look you don't need ?.
on your example, it's optional chaining, and one more, please add you cunstruction to the ref
const peerConnection = useRef<RTCPeerConnection>(
new RTCPeerConnection({
iceServers: []
})
);
because in your case you create ne instance each time when function run
CodePudding user response:
useRef
role is to hold a reference to ´PeerConnection´ component and expose its properties and methods (functions) to ´peerConnection.current´.
´useRef´ persists its value across component rerender cycles. In some worst-case scenarios, a child component where ´useRef´ hold reference should not mounted and you can't access its member methods and properties.
Optional chaining operator (?) make code safe from crashing by avoiding to call components methods or properties while not exposed.