Back to Blog
React Native

Real-Time Magic: A No-BS Guide to WebSockets in React Native |

11/16/2025
5 min read
 Real-Time Magic: A No-BS Guide to WebSockets in React Native |

Tired of constant API polling? Learn how to use WebSockets in React Native for live chats, gaming, and real-time data. Step-by-step tutorial, best practices, and FAQs included. Level up your skills with CoderCrafter's courses!

 Real-Time Magic: A No-BS Guide to WebSockets in React Native |

Real-Time Magic: A No-BS Guide to WebSockets in React Native |

Real-Time Magic: A No-BS Guide to WebSockets in React Native

Let's be real. We live in a world of instant gratification. We expect our food delivery app to show us the rider's live location, our trading app to flash the latest stock prices, and our group chats to update without us hitting "refresh." This isn't just cool tech—it's the standard.

So, how do you build these snappy, real-time features into your React Native apps? The answer, more often than not, is WebSockets.

If you're tired of your app constantly asking the server "Any updates? How about now? Now?" (a process called polling), then you're in the right place. In this deep dive, we're going to break down WebSockets from "what even is that?" to "heck yeah, I built that!". We'll cover the code, the gotchas, and the best practices to make your app feel truly alive.

Alright, What Exactly Are WebSockets?

Imagine you're calling a customer service hotline. You explain your problem, they put you on hold, you listen to terrible music for 10 minutes, you check back in, and the cycle repeats. This is like traditional HTTP requests—a one-off, request-response conversation.

Now, imagine instead you call them and they just stay on the line. You can talk whenever you want, and they can talk back whenever they have an update. No hold music, no repeating yourself. The line is just open. This is a WebSocket connection.

In technical terms, WebSocket is a communication protocol that provides full-duplex (meaning both ways simultaneously), persistent communication channels over a single TCP connection. Once the initial "handshake" is done using HTTP, the connection is upgraded, and a continuous line of communication is established between the client (your React Native app) and the server.

This is a game-changer for features where low latency and instant updates are non-negotiable.

Why Should I Care? Real-World Use Cases

This isn't just theoretical. You use apps powered by WebSockets every single day.

  • Live Chat & Messaging: WhatsApp, Telegram, Slack. Messages appear instantly for all participants.

  • Collaborative Apps: Google Docs, Figma. See your teammate's cursor moving and edits happening in real-time.

  • Live Sports & Financial Trading Apps: Stock prices and scores update without you lifting a finger.

  • Multiplayer Gaming: Every move your opponent makes is relayed to your device instantly.

  • Live Location Tracking: Uber, Swiggy, Zomato. Watching your driver or delivery partner navigate towards you.

  • IoT Dashboards: Monitoring smart home devices, getting instant alerts if a sensor is triggered.

See? It's everywhere. And now, you're going to learn how to build it.

Hands-On: Building a Simple Live Feed in React Native

Let's stop talking and start coding. We'll create a simple app that connects to a public, test WebSocket server and displays live messages. For this demo, we'll use the popular react-native-websocket library, but the concepts apply to others as well.

Step 1: Project Setup and Installation

First, create a new React Native project (or navigate to your existing one).

bash

npx react-native init LiveFeedApp
cd LiveFeedApp

Now, let's install the library.

bash

npm install react-native-websocket
# If you're using CocoaPods for iOS
cd ios && pod install && cd ..

Step 2: The Code - Connecting, Sending, and Receiving

Here's the complete code for a LiveFeedScreen.js. We'll break it down afterward.

javascript

// LiveFeedScreen.js
import React, { useState, useEffect, useRef } from 'react';
import { View, Text, TextInput, TouchableOpacity, FlatList, Alert } from 'react-native';
import WSS from 'react-native-websocket';

const LiveFeedScreen = () => {
  // State for the messages we receive
  const [messages, setMessages] = useState([]);
  // State for the message we are about to send
  const [inputMessage, setInputMessage] = useState('');
  // A ref to access the WebSocket instance directly
  const ws = useRef(null);

  useEffect(() => {
    // This is a public test server. For a real app, you'd use your own server URL.
    const socketUrl = 'wss://echo.websocket.events';

    // Initialize the WebSocket connection
    ws.current = new WSS(socketUrl);
    
    // Event: When the connection opens
    ws.current.onopen = () => {
      console.log('WebSocket Connected!');
      setMessages(prev => [...prev, { id: Date.now(), text: 'System: Connected to server!' }]);
    };

    // Event: When a message is received from the server
    ws.current.onmessage = (e) => {
      console.log('Message from server:', e.data);
      // The test server echoes our message. Let's add it to the list.
      if (e.data !== 'echo.websocket.events sponsored by Lob.com') { // Ignore the initial sponsor message
        setMessages(prev => [...prev, { id: Date.now(), text: `Echo: ${e.data}` }]);
      }
    };

    // Event: When the connection closes
    ws.current.onclose = (e) => {
      console.log('WebSocket Disconnected:', e.reason);
      setMessages(prev => [...prev, { id: Date.now(), text: `System: Disconnected!` }]);
    };

    // Event: When there's an error
    ws.current.onerror = (e) => {
      console.error('WebSocket Error:', e.message);
      Alert.alert('WebSocket Error', e.message);
    };

    // Cleanup: Close the connection when the component unmounts
    return () => {
      if (ws.current && ws.current.readyState === WSS.OPEN) {
        ws.current.close();
      }
    };
  }, []); // Empty dependency array means this effect runs once on mount.

  // Function to send a message
  const sendMessage = () => {
    if (inputMessage.trim() && ws.current && ws.current.readyState === WSS.OPEN) {
      ws.current.send(inputMessage);
      setInputMessage(''); // Clear the input
    }
  };

  return (
    <View style={{ flex: 1, padding: 20 }}>
      <Text style={{ fontSize: 24, fontWeight: 'bold', marginBottom: 20 }}>
        Live Feed
      </Text>

      {/* Message List */}
      <FlatList
        data={messages}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({ item }) => (
          <View style={{ padding: 10, borderBottomWidth: 1, borderBottomColor: '#ccc' }}>
            <Text>{item.text}</Text>
          </View>
        )}
        style={{ flex: 1, marginBottom: 20 }}
      />

      {/* Input and Send Button */}
      <View style={{ flexDirection: 'row' }}>
        <TextInput
          style={{
            flex: 1,
            borderWidth: 1,
            borderColor: '#ccc',
            padding: 10,
            marginRight: 10,
            borderRadius: 5,
          }}
          value={inputMessage}
          onChangeText={setInputMessage}
          placeholder="Type a message..."
        />
        <TouchableOpacity
          onPress={sendMessage}
          style={{
            backgroundColor: '#007BFF',
            paddingHorizontal: 20,
            justifyContent: 'center',
            borderRadius: 5,
          }}
        >
          <Text style={{ color: 'white' }}>Send</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

export default LiveFeedScreen;

Step 3: Understanding the Key Parts

  1. useRef for the Socket: We use useRef to hold the WebSocket instance because its value persists across re-renders without causing them, unlike useState.

  2. The useEffect Hook: This is where the magic starts. On component mount, it creates the WebSocket connection and sets up all the event listeners (onopen, onmessage, onclose, onerror).

  3. Event Listeners:

    • onopen: Fires when the connection is established. Perfect for initial setup.

    • onmessage: The most important one. Fires every time the server sends data. We take that data (e.data) and update our state.

    • onclose & onerror: Crucial for handling disconnections and network issues gracefully.

  4. The Cleanup Function: This is a critical best practice. When the component unmounts (e.g., user navigates away), we close the WebSocket connection to prevent memory leaks.

  5. sendMessage Function: When the user hits "Send", we check if the connection is open (ws.current.readyState === WSS.OPEN) and then use ws.current.send() to transmit the message.

Run this app, and you'll have a basic but fully functional real-time messaging feed!

Leveling Up: Best Practices You Can't Ignore

Building a toy app is one thing; building a production-grade real-time feature is another. Here are the pro-tips.

  1. Connection Management: Implement reconnection logic. If the connection drops, try to reconnect with an exponential backoff (wait 1s, then 2s, then 4s, etc.).

  2. Heartbeats/Pings: Some networks or proxies might kill idle connections. Send a periodic "ping" message to the server to keep the connection alive.

  3. Handle App State: What happens when the app goes to the background? On iOS, you might need to manage the connection carefully to avoid being suspended. Libraries like react-native-netinfo can help you listen to network state changes.

  4. Message Protocols: For complex apps, don't just send plain text. Use a structured format like JSON so you can include message types, sender IDs, timestamps, etc.

    javascript

    // Instead of just:
    ws.send("Hello");
    
    // Do this:
    ws.send(JSON.stringify({
      type: 'chat_message',
      userId: 'user_123',
      text: 'Hello',
      timestamp: Date.now()
    }));
  5. Security: Always use wss:// (WebSocket Secure) in production, which is the equivalent of https://. Validate and sanitize all messages on both the client and server side.

Mastering these concepts is what separates a hobbyist from a professional developer. Speaking of which, if you're looking to solidify your understanding of full-stack development and build complex, real-world applications...

To learn professional software development courses such as Python Programming, Full Stack Development, and MERN Stack, visit and enroll today at codercrafter.in. Our project-based curriculum is designed to take you from beginner to job-ready.

FAQs: Quick-Fire Round

Q: Can I use the native WebSocket API in React Native?
A: Yes! React Native has a built-in WebSocket implementation. However, community libraries often provide a more React-friendly API and handle some of the platform-specific quirks for you.

Q: What are some popular alternatives to react-native-websocket?
A: socket.io-client is incredibly popular, especially if your backend is also using Socket.IO. It provides additional features like automatic reconnection and rooms.

Q: How do I test my WebSocket integration?
A: You can use tools like Postman (which now supports WebSockets) or simple command-line tools like wscat. For unit testing, you can mock the WebSocket object.

Q: My WebSocket works on Android but not on iOS. Why?
A: Check your App Transport Security (ATS) settings in your Info.plist file. iOS blocks non-secure connections (ws://) by default. You must use wss:// or configure ATS exceptions for development.

Conclusion: Your App, Now in Real-Time

And there you have it! WebSockets are your ticket to building dynamic, engaging, and modern React Native applications. We've walked through the core concept, built a working example, and discussed the critical best practices to ensure your implementation is robust.

It might feel like a lot at first, but the pattern is always the same: Connect, Listen, Send, Handle Disconnections. Once you get the hang of it, a whole new world of app possibilities opens up.

So, fire up your code editor, plug in the example above, and start experimenting. Break it, fix it, and add your own features. The best way to learn is by doing.

And remember, if you want to fast-track your journey and build a killer portfolio with guided mentorship...

We at CoderCrafter are passionate about turning coding enthusiasts into industry-ready developers. Check out our comprehensive courses in Full Stack Development and more at codercrafter.in. Let's build the future, together!

Related Articles

Call UsWhatsApp