React & React NativeHooksConnectionsuseFetchConnectionsCountByUserId

useFetchConnectionsCountByUserId

Overview

The useFetchConnectionsCountByUserId hook fetches the total number of established connections for any specified user. This is a public endpoint that allows you to retrieve connection counts for any user without authentication, making it useful for displaying user statistics and social proof.

Usage Example

import { useFetchConnectionsCountByUserId } from "@replyke/react-js";
 
function UserConnectionsCounter({ targetUserId }: { targetUserId: string }) {
  const fetchConnectionsCountByUserId = useFetchConnectionsCountByUserId();
 
  const getUserConnectionsCount = async () => {
    try {
      const result = await fetchConnectionsCountByUserId({ userId: targetUserId });
      console.log(`This user has ${result.count} connections`);
    } catch (error) {
      console.error("Failed to fetch user connections count:", error.message);
    }
  };
 
  return <button onClick={getUserConnectionsCount}>Check User's Connections</button>;
}

Advanced Usage with State Management

import { useFetchConnectionsCountByUserId } from "@replyke/react-js";
import { useState, useEffect } from "react";
 
function UserProfileStats({
  userId,
  username
}: {
  userId: string;
  username: string;
}) {
  const fetchConnectionsCountByUserId = useFetchConnectionsCountByUserId();
  const [connectionsCount, setConnectionsCount] = useState<number | null>(null);
  const [loading, setLoading] = useState(false);
 
  useEffect(() => {
    if (!userId) return;
 
    const loadCount = async () => {
      setLoading(true);
      try {
        const result = await fetchConnectionsCountByUserId({ userId });
        setConnectionsCount(result.count);
      } catch (error) {
        console.error("Failed to load connection count:", error);
        setConnectionsCount(0);
      } finally {
        setLoading(false);
      }
    };
 
    loadCount();
  }, [userId, fetchConnectionsCountByUserId]);
 
  return (
    <div className="user-profile-stats">
      <h3>{username}</h3>
      <div className="stats">
        {loading ? (
          <span>Loading...</span>
        ) : (
          <>
            <span className="count">{connectionsCount?.toLocaleString() ?? 0}</span>
            <span className="label">Professional Connections</span>
          </>
        )}
      </div>
    </div>
  );
}

Usage in User Discovery Lists

import { useFetchConnectionsCountByUserId } from "@replyke/react-js";
import { useState, useEffect } from "react";
 
interface User {
  id: string;
  username: string;
  displayName?: string;
  avatar?: string;
  bio?: string;
}
 
interface UserWithConnectionCount extends User {
  connectionsCount: number;
  connectionsLoading: boolean;
}
 
function UserDiscoveryCard({ user }: { user: User }) {
  const fetchConnectionsCountByUserId = useFetchConnectionsCountByUserId();
  const [connectionsCount, setConnectionsCount] = useState<number>(0);
  const [loading, setLoading] = useState(true);
 
  useEffect(() => {
    const loadConnectionCount = async () => {
      try {
        const result = await fetchConnectionsCountByUserId({ userId: user.id });
        setConnectionsCount(result.count);
      } catch (error) {
        console.error(`Failed to load connection count for ${user.username}:`, error);
        setConnectionsCount(0);
      } finally {
        setLoading(false);
      }
    };
 
    loadConnectionCount();
  }, [user.id]);
 
  return (
    <div className="user-discovery-card">
      <div className="user-avatar">
        {user.avatar ? (
          <img src={user.avatar} alt={`${user.username} avatar`} />
        ) : (
          <div className="avatar-placeholder">{user.username[0].toUpperCase()}</div>
        )}
      </div>
 
      <div className="user-info">
        <h4>{user.displayName || user.username}</h4>
        <p>@{user.username}</p>
        {user.bio && <p className="bio">{user.bio}</p>}
      </div>
 
      <div className="user-stats">
        {loading ? (
          <span className="connections-loading">Loading...</span>
        ) : (
          <div className="connections-count">
            <span className="count">{connectionsCount.toLocaleString()}</span>
            <span className="label">connections</span>
          </div>
        )}
      </div>
 
      <div className="card-actions">
        <button className="connect-btn">Connect</button>
        <button className="view-profile-btn">View Profile</button>
      </div>
    </div>
  );
}
 
function UserDiscoveryList({ users }: { users: User[] }) {
  return (
    <div className="user-discovery-list">
      <h2>Discover People</h2>
      <div className="users-grid">
        {users.map(user => (
          <UserDiscoveryCard key={user.id} user={user} />
        ))}
      </div>
    </div>
  );
}

Usage for Leaderboards and Rankings

import { useFetchConnectionsCountByUserId } from "@replyke/react-js";
import { useState, useEffect } from "react";
 
interface LeaderboardUser {
  id: string;
  username: string;
  displayName?: string;
  avatar?: string;
}
 
interface UserWithRank extends LeaderboardUser {
  connectionsCount: number;
  rank: number;
}
 
function ConnectionsLeaderboard({ users }: { users: LeaderboardUser[] }) {
  const fetchConnectionsCountByUserId = useFetchConnectionsCountByUserId();
  const [rankedUsers, setRankedUsers] = useState<UserWithRank[]>([]);
  const [loading, setLoading] = useState(true);
 
  useEffect(() => {
    const loadAllConnectionCounts = async () => {
      setLoading(true);
      try {
        const usersWithCounts = await Promise.all(
          users.map(async (user) => {
            try {
              const result = await fetchConnectionsCountByUserId({ userId: user.id });
              return { ...user, connectionsCount: result.count };
            } catch (error) {
              console.error(`Failed to load count for ${user.username}:`, error);
              return { ...user, connectionsCount: 0 };
            }
          })
        );
 
        // Sort by connection count and add ranks
        const sorted = usersWithCounts
          .sort((a, b) => b.connectionsCount - a.connectionsCount)
          .map((user, index) => ({ ...user, rank: index + 1 }));
 
        setRankedUsers(sorted);
      } catch (error) {
        console.error("Failed to load leaderboard:", error);
      } finally {
        setLoading(false);
      }
    };
 
    loadAllConnectionCounts();
  }, [users]);
 
  const getRankIcon = (rank: number) => {
    switch (rank) {
      case 1: return "🥇";
      case 2: return "🥈";
      case 3: return "🥉";
      default: return `#${rank}`;
    }
  };
 
  return (
    <div className="connections-leaderboard">
      <h2>Most Connected Users</h2>
 
      {loading ? (
        <div>Loading leaderboard...</div>
      ) : (
        <div className="leaderboard-list">
          {rankedUsers.map(user => (
            <div key={user.id} className={`leaderboard-item rank-${user.rank}`}>
              <div className="rank">
                <span className="rank-icon">{getRankIcon(user.rank)}</span>
              </div>
 
              <div className="user-info">
                {user.avatar && (
                  <img
                    src={user.avatar}
                    alt={`${user.username} avatar`}
                    className="avatar"
                  />
                )}
                <div className="user-details">
                  <h4>{user.displayName || user.username}</h4>
                  <p>@{user.username}</p>
                </div>
              </div>
 
              <div className="connections-stat">
                <span className="count">{user.connectionsCount.toLocaleString()}</span>
                <span className="label">connections</span>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

Usage for Network Size Comparison

import { useFetchConnectionsCountByUserId } from "@replyke/react-js";
import { useFetchConnectionsCount } from "@replyke/react-js";
import { useState, useEffect } from "react";
 
function NetworkComparison({ compareWithUserId, compareWithUsername }: {
  compareWithUserId: string;
  compareWithUsername: string;
}) {
  const fetchConnectionsCountByUserId = useFetchConnectionsCountByUserId();
  const fetchMyConnectionsCount = useFetchConnectionsCount();
 
  const [myCount, setMyCount] = useState<number>(0);
  const [theirCount, setTheirCount] = useState<number>(0);
  const [loading, setLoading] = useState(true);
 
  useEffect(() => {
    const loadCounts = async () => {
      setLoading(true);
      try {
        const [myResult, theirResult] = await Promise.all([
          fetchMyConnectionsCount(),
          fetchConnectionsCountByUserId({ userId: compareWithUserId })
        ]);
 
        setMyCount(myResult.count);
        setTheirCount(theirResult.count);
      } catch (error) {
        console.error("Failed to load connection counts for comparison:", error);
      } finally {
        setLoading(false);
      }
    };
 
    loadCounts();
  }, [compareWithUserId]);
 
  const getComparisonMessage = () => {
    if (myCount === theirCount) {
      return `You and ${compareWithUsername} have the same number of connections!`;
    } else if (myCount > theirCount) {
      const difference = myCount - theirCount;
      return `You have ${difference} more connection${difference === 1 ? '' : 's'} than ${compareWithUsername}`;
    } else {
      const difference = theirCount - myCount;
      return `${compareWithUsername} has ${difference} more connection${difference === 1 ? '' : 's'} than you`;
    }
  };
 
  const getPercentageDifference = () => {
    if (myCount === 0 && theirCount === 0) return 0;
    if (myCount === 0) return 100;
    if (theirCount === 0) return -100;
 
    return Math.round(((theirCount - myCount) / myCount) * 100);
  };
 
  if (loading) return <div>Comparing networks...</div>;
 
  return (
    <div className="network-comparison">
      <h3>Network Size Comparison</h3>
 
      <div className="comparison-chart">
        <div className="comparison-bar">
          <div className="my-connections">
            <div className="bar" style={{ width: `${(myCount / Math.max(myCount, theirCount)) * 100}%` }} />
            <span className="label">You: {myCount.toLocaleString()}</span>
          </div>
 
          <div className="their-connections">
            <div className="bar" style={{ width: `${(theirCount / Math.max(myCount, theirCount)) * 100}%` }} />
            <span className="label">{compareWithUsername}: {theirCount.toLocaleString()}</span>
          </div>
        </div>
 
        <div className="comparison-summary">
          <p>{getComparisonMessage()}</p>
 
          {getPercentageDifference() !== 0 && (
            <p className="percentage-diff">
              {getPercentageDifference() > 0 ? '+' : ''}{getPercentageDifference()}% difference
            </p>
          )}
        </div>
      </div>
 
      <div className="network-insights">
        <h4>Network Insights</h4>
        <ul>
          {myCount > 100 && <li>🌟 You have a strong professional network!</li>}
          {theirCount > 100 && <li>🔥 {compareWithUsername} is well-connected!</li>}
          {Math.abs(myCount - theirCount) < 10 && <li>🤝 You both have similarly sized networks</li>}
          {myCount === 0 && <li>💡 Start building your network by connecting with colleagues</li>}
        </ul>
      </div>
    </div>
  );
}

Usage in User Search Results

import { useFetchConnectionsCountByUserId } from "@replyke/react-js";
import { useState, useEffect } from "react";
 
interface SearchResultUser {
  id: string;
  username: string;
  displayName?: string;
  avatar?: string;
  bio?: string;
  matchScore?: number;
}
 
function UserSearchResult({ user }: { user: SearchResultUser }) {
  const fetchConnectionsCountByUserId = useFetchConnectionsCountByUserId();
  const [connectionsCount, setConnectionsCount] = useState<number | null>(null);
 
  useEffect(() => {
    const loadCount = async () => {
      try {
        const result = await fetchConnectionsCountByUserId({ userId: user.id });
        setConnectionsCount(result.count);
      } catch (error) {
        console.error("Failed to load connection count:", error);
      }
    };
 
    loadCount();
  }, [user.id]);
 
  const getNetworkSize = () => {
    if (connectionsCount === null) return "Loading...";
    if (connectionsCount === 0) return "New to the network";
    if (connectionsCount < 50) return "Growing network";
    if (connectionsCount < 200) return "Well connected";
    if (connectionsCount < 500) return "Highly connected";
    return "Super connector";
  };
 
  return (
    <div className="user-search-result">
      <div className="user-avatar">
        {user.avatar ? (
          <img src={user.avatar} alt={`${user.username} avatar`} />
        ) : (
          <div className="avatar-placeholder">{user.username[0].toUpperCase()}</div>
        )}
      </div>
 
      <div className="user-details">
        <div className="user-header">
          <h4>{user.displayName || user.username}</h4>
          <span className="username">@{user.username}</span>
          {user.matchScore && (
            <span className="match-score">{Math.round(user.matchScore * 100)}% match</span>
          )}
        </div>
 
        {user.bio && <p className="bio">{user.bio}</p>}
 
        <div className="network-info">
          <span className="connections-count">
            {connectionsCount !== null
              ? `${connectionsCount.toLocaleString()} connections`
              : "Loading connections..."
            }
          </span>
          <span className="network-size-badge">{getNetworkSize()}</span>
        </div>
      </div>
 
      <div className="search-actions">
        <button className="connect-btn">Connect</button>
        <button className="view-profile-btn">View Profile</button>
      </div>
    </div>
  );
}
 
function UserSearchResults({ users }: { users: SearchResultUser[] }) {
  return (
    <div className="user-search-results">
      {users.map(user => (
        <UserSearchResult key={user.id} user={user} />
      ))}
    </div>
  );
}

Parameters & Returns

Parameters

The hook returns a function that accepts an object with the following field:

ParameterTypeRequiredDescription
userIdstringYesThe ID of the user whose connection count to fetch

Returns

The function returns a Promise that resolves to a ConnectionCountResponse object containing:

FieldTypeDescription
countnumberThe total number of connections this user has

Error Handling

The hook will throw errors in the following cases:

  • No project is specified
  • No user ID is provided
  • Network connection issues

Use Cases

This hook is perfect for:

User Discovery & Social Proof:

  • Displaying connection counts on user profiles
  • User search results with network size indicators
  • Social proof in user recommendations

Analytics & Rankings:

  • Leaderboards of most connected users
  • Network size comparisons
  • User activity metrics

UI Components:

  • User cards with connection statistics
  • Profile badges showing network size
  • Discovery feeds with social context

Performance Considerations

  1. Caching: Cache results to avoid repeated API calls for the same user
  2. Batch Loading: Consider batching requests when loading multiple users
  3. Rate Limiting: Be mindful of rate limits when loading many user counts
  4. Error Handling: Provide graceful fallbacks when counts fail to load

Privacy Considerations

Since this is a public endpoint:

  • Users may want to hide their connection counts
  • Consider implementing privacy settings
  • Respect user preferences for network visibility
  • Provide opt-out mechanisms
  • useFetchConnectionsCount - Get connection count for current user (authenticated)
  • useFetchConnectionsByUserId - Get detailed connections for any user
  • useFetchConnectionStatus - Check connection status with specific user
  • useConnectionManager - Comprehensive connection state management