๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ’ก ๊ณตํ•™์ž/์ฝ”๋”ฉ ์„œํ•‘

[react native]์›น์†Œ์ผ“ ์ ์šฉํ•˜๊ธฐ

๋ฆฌ์•กํŠธ ๋„ค์ดํ‹ฐ๋ธŒ์— ์›น์†Œ์ผ“ ์ ์šฉํ•˜๊ธฐ

๋ฆฌ์•กํŠธ ๋„ค์ดํ‹ฐ๋ธŒ์—์„œ ์›น์†Œ์ผ“ ํ†ต์‹ ์„ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด์„œ WebSocket์„ ์‚ฌ์šฉํ•˜๋ผ๊ณ  ๊ถŒ์žฅํ•œ๋‹ค.

ํŽ˜์ด์Šค๋ถ ๊ณต์‹๋ฌธ์„œ - https://reactnative.dev/docs/network#websocket-support

ํ˜„์žฌ ํ•จ์ˆ˜ํ˜• ์ปดํฌ๋„ŒํŠธ๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ๋Š”๋ฐ, ์ฒ˜์Œ์— ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์ƒ์„ฑ๋  ๋•Œ ์ตœ์ดˆ 1ํšŒ๋งŒ ์›น์†Œ์ผ“์˜ ์ฑ„๋„์„ ์ƒ์„ฑํ•ด์•ผ ํ•œ๋‹ค. ๋”ฐ๋ผ์„œ, useEffect hook์„ ์‚ฌ์šฉํ•ด์„œ ์ตœ์ดˆ 1ํšŒ ์›น์†Œ์ผ“์„ ์ •์˜ํ–ˆ๋‹ค.

useEffect(() => {
        let ws = new WebSocket(`ws://127.0.0.1:8000/ws/room/`)
        ws.onopen = () => {
            // connection opened
            console.log('connected')
        };

        ws.onmessage = (e) => {
            // a message was received
            console.log(e.data);
        };

        ws.onerror = (e) => {
            // an error occurred
            console.log(e.message);
        };

        ws.onclose = (e) => {
            // connection closed
            console.log(e.code, e.reason);
        };

        return () => {
            ws.close();
        };
    }, [])

์›น์†Œ์ผ“ ์ธ์Šคํ„ด์Šค์˜ scope ๋ฌธ์ œ

ํ•˜์ง€๋งŒ ์ด๋ ‡๊ฒŒ useEffect hook ์•ˆ์—์„œ ์ •์˜๊ฐ€ ๋˜๊ธฐ ๋•Œ๋ฌธ์— ๋‹ค๋ฅธ ํ•จ์ˆ˜์—์„œ ์›น์†Œ์ผ“ ์ธ์Šคํ„ด์Šค๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๊ฒŒ ๋œ๋‹ค. ์ด๋ฅผ ํ•ด๊ฒฐํ•˜๋Š” ๋ฐฉ์•ˆ์œผ๋กœ useRef hook์„ ์‚ฌ์šฉํ•˜๋ผ๊ณ  ํ•œ๋‹ค.

ํ•ด๊ฒฐ๋ฐฉ์•ˆ - https://stackoverflow.com/questions/60152922/proper-way-of-using-react-hooks-websockets

const ws = useRef(null);
useEffect(() => {
    ws.current = new WebSocket(`ws://127.0.0.1:8000/ws/room/`)
    console.log(ws.current)
    ws.current.onopen = () => {
        // connection opened
        console.log('connected')
        // send a message
    };

    ws.current.onmessage = (e) => {
        // a message was received
        console.log(e.data);
    };

    ws.current.onerror = (e) => {
        // an error occurred
        console.log(e.message);
    };

    ws.current.onclose = (e) => {
        // connection closed
        console.log(e.code, e.reason);
    };

    return () => {
        ws.current.close();
    };
}, [])

ref๋Š” ๋‹จ์ˆœํžˆ DOM๋ฟ๋งŒ ์•„๋‹ˆ๋ผ, ๊ฐ์ฒด๋“ค์„ ์ €์žฅํ•˜๋Š” ๊ธฐ๋Šฅ์œผ๋กœ๋„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค๊ณ  ํ•œ๋‹ค.

The useRef() Hook isn’t just for DOM refs. The “ref” object is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class. more

๋ฐ˜์‘ํ˜•