¡Claro! Optimizar y estructurar tu código en componentes más pequeños no solo mejora la mantenibilidad, sino que también facilita la reutilización y la legibilidad. A continuación, te proporcionaré una guía paso a paso para refactorizar tu aplicación SpotifyClone en componentes más manejables y aplicar algunas buenas prácticas de optimización.
1. Separa el Código en Componentes
Dividir tu aplicación en componentes más pequeños es fundamental para la mantenibilidad. A continuación, se detallan algunos componentes que puedes crear:
- Navbar: Barra de navegación superior.
- Sidebar: Barra lateral con las opciones de navegación.
- Player: Controles de reproducción y barra de ahora reproduciendo.
- SongList: Lista de canciones.
- PlaylistInfo: Información de la playlist.
- YouTubePlayer: Componente para gestionar el reproductor de YouTube.
2. Crear Componentes Individuales
a. YouTubePlayer.tsx
Este componente manejará toda la lógica relacionada con el reproductor de YouTube.
// components/YouTubePlayer.tsx
import React, { useEffect, useRef } from "react";
import YouTube, { YouTubeProps, YouTubePlayer } from "react-youtube";
interface YouTubePlayerProps {
videoId: string;
isPlaying: boolean;
onEnd: () => void;
onStateChange?: YouTubeProps["onStateChange"];
volume: number;
setDuration: (duration: number) => void;
setCurrentTime: (time: number) => void;
}
const YouTubePlayer: React.FC<YouTubePlayerProps> = ({
videoId,
isPlaying,
onEnd,
onStateChange,
volume,
setDuration,
,
setCurrentTime,
}) => {
const playerRef = useRef<YouTubePlayer | null>(null);
const onReady: YouTubeProps["onReady"] = (event) => {
playerRef.current = event.target;
setDuration(event.target.getDuration());
event.target.setVolume(volume);
if (isPlaying) {
event.target.playVideo();
}
};
useEffect(() => {
if (playerRef.current) {
if (isPlaying) {
playerRef.current.playVideo();
} else {
playerRef.current.pauseVideo();
}
}
}, [isPlaying]);
useEffect(() => {
if (playerRef.current) {
playerRef.current.setVolume(volume);
}
}, [volume]);
const opts: YouTubeProps["opts"] = {
height: "0",
width: "0",
playerVars: {
autoplay: 0,
controls: 0,
disablekb: 1,
fs: 0,
modestbranding: 1,
rel: 0,
},
};
// Actualizar el tiempo actual y la duración
useEffect(() => {
let intervalId: NodeJS.Timeout | null = null;
if (playerRef.current && isPlaying) {
intervalId = setInterval(() => {
const current = playerRef.current!.getCurrentTime();
const dura = playerRef.current!.getDuration();
setCurrentTime(current);
setDuration(dura);
}, 1000);
}
return () => {
if (intervalId) clearInterval(intervalId);
};
}, [isPlaying, setCurrentTime, setDuration]);
return (
<YouTube
videoId={videoId}
opts={opts}
onReady={onReady}
onEnd={onEnd}
onStateChange={onStateChange}
/>
);
};
export default YouTubePlayer;
b. Navbar.tsx
Componente para la barra de navegación superior.
// components/Navbar.tsx
import React from "react";
import { Button } from "./ui/button";
import { Menu, X, Home, Search, Library } from "lucide-react";
import { Input } from "./ui/input";
interface NavbarProps {
isMobile: boolean;
isSidebarOpen: boolean;
toggleSidebar: () => void;
}
const Navbar: React.FC<NavbarProps> = ({
isMobile,
isSidebarOpen,
toggleSidebar,
}) => {
return (
<div className="flex items-center justify-between p-4 bg-gray-900">
{isMobile ? (
<div className="flex-1">
<Input
type="text"
placeholder="¿Qué quieres reproducir?"
className="w-full px-4 py-2 text-sm rounded-full bg-transparent placeholder-white text-white focus:ring-red-500"
/>
</div>
) : (
<>
<Button
variant="ghost"
size="icon"
className="text-gray-400 hover:text-white"
onClick={toggleSidebar}
aria-label={isSidebarOpen ? "Cerrar menú" : "Abrir menú"}
>
{isSidebarOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
</Button>
<div className="flex-1 max-w-xl mx-4">
<Input
type="text"
placeholder="¿Qué quieres reproducir?"
className="w-full px-4 py-2 text-sm rounded-full bg-gray-800 placeholder-gray-400 text-white focus:ring-green-500"
/>
</div>
<div className="flex items-center space-x-4">
<Button
variant="ghost"
size="icon"
className="text-gray-400 hover:text-white"
aria-label="Usuario"
>
{/* SVG de Usuario */}
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M12 12C15.3137 12 18 9.31371 18 6C18 2.68629 15.3137 0 12 0C8.68629 0 6 2.68629 6 6C6 9.31371 8.68629 12 12 12Z"
fill="currentColor"
/>
<path
d="M12 14C8.13401 14 0 16.1188 0 19V24H24V19C24 16.1188 15.866 14 12 14Z"
fill="currentColor"
/>
</svg>
</Button>
<img
src="https://i.postimg.cc/Kjx7YXWv/yo.webp"
alt="Usuario"
className="w-8 h-8 rounded-full"
/>
</div>
</>
)}
</div>
);
};
export default Navbar;
c. Sidebar.tsx
Componente para la barra lateral.
// components/Sidebar.tsx
import React from "react";
import { Button } from "./ui/button";
import { Home, Search, Library } from "lucide-react";
interface SidebarProps {
isSidebarOpen: boolean;
isMobile: boolean;
closeSidebar: () => void;
}
const Sidebar: React.FC<SidebarProps> = ({ isSidebarOpen, isMobile, closeSidebar }) => {
return (
<div
className={`fixed inset-y-0 left-0 z-50 w-64 p-4 overflow-y-auto bg-gray-900 transform ${
isSidebarOpen ? "translate-x-0" : "-translate-x-full"
} transition-transform duration-300 ease-in-out
lg:translate-x-0 lg:static lg:inset-auto`}
>
<div className="mb-6">
<Button
variant="ghost"
className="w-full justify-start text-gray-400 hover:text-white mb-2"
aria-label="Inicio"
>
<Home className="w-5 h-5 mr-3" />
Inicio
</Button>
<Button
variant="ghost"
className="w-full justify-start text-gray-400 hover:text-white mb-2"
aria-label="Buscar"
>
<Search className="w-5 h-5 mr-3" />
Buscar
</Button>
<Button
variant="ghost"
className="w-full justify-start text-gray-400 hover:text-white"
aria-label="Tu biblioteca"
>
<Library className="w-5 h-5 mr-3" />
Tu biblioteca
</Button>
</div>
<div className="pt-4 border-t border-gray-800">
<h2 className="mb-4 text-sm font-semibold text-gray-400 uppercase">
Playlists
</h2>
<Button
variant="ghost"
className="w-full justify-start text-white bg-gray-800 hover:bg-gray-700 mb-2 flex items-center"
aria-label="Time Free"
>
<div className="w-12 h-12 mr-3 bg-gradient-to-br from-purple-700 to-blue-400 rounded-md"></div>
Time Free
</Button>
</div>
</div>
);
};
export default Sidebar;
d. PlaylistInfo.tsx
Muestra la información de la playlist.
// components/PlaylistInfo.tsx
import React from "react";
interface PlaylistInfoProps {
playlist: {
name: string;
description: string;
owner: string;
timesSaved: number;
songsCount: number;
totalDuration: string;
coverImage: string;
};
isMobile: boolean;
}
const PlaylistInfo: React.FC<PlaylistInfoProps> = ({ playlist, isMobile }) => {
return (
<div className="flex flex-col lg:flex-row items-start mb-6">
<img
src={playlist.coverImage || "/placeholder.svg"}
alt="Playlist cover"
className="w-40 h-40 mr-6 object-cover rounded-md"
/>
<div className="text-left">
{!isMobile && (
<p className="text-sm font-medium">Playlist pública</p>
)}
<h1 className="text-5xl font-bold mb-2">{playlist.name}</h1>
<p className="text-sm">{playlist.description}</p>
<div className="flex items-center mt-2">
<img
src="https://i.postimg.cc/Kjx7YXWv/yo.webp"
alt="Propietario"
className="w-6 h-6 rounded-full mr-2"
/>
<div className="flex flex-col">
<span className="text-sm">{playlist.owner}</span>
<span className="text-sm text-gray-400">
{`${playlist.timesSaved} veces guardada • ${playlist.songsCount} canciones, ${playlist.totalDuration}`}
</span>
</div>
</div>
</div>
</div>
);
};
export default PlaylistInfo;
e. SongList.tsx
Lista de canciones.
// components/SongList.tsx
import React from "react";
interface Song {
title: string;
artist: string;
album: string;
added: string;
duration?: number;
youtubeId?: string;
}
interface SongListProps {
songs: Song[];
isMobile: boolean;
onSelectSong: (song: Song) => void;
}
const SongList: React.FC<SongListProps> = ({ songs, isMobile, onSelectSong }) => {
const getYouTubeThumbnail = (youtubeId: string): string =>
`https://img.youtube.com/vi/${youtubeId}/hqdefault.jpg`;
const formatTime = (seconds: number): string => {
const minutes = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
const minutesStr = minutes < 10 ? `0${minutes}` : `${minutes}`;
const secondsStr = secs < 10 ? `0${secs}` : `${secs}`;
return `${minutesStr}:${secondsStr}`;
};
return (
<table className="w-full">
<thead>
<tr className="text-left text-sm text-gray-400 border-b border-gray-800">
{!isMobile && <th className="pb-2">#</th>}
<th className="pb-2">Título</th>
{!isMobile && <th className="pb-2">Álbum</th>}
{!isMobile && <th className="pb-2">Fecha en que se agregó</th>}
{!isMobile && (
<th className="pb-2">
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M8 3.33337V12.6667"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
<path
d="M3.33331 8H12.6666"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</th>
)}
</tr>
</thead>
<tbody>
{songs.map((track, index) => (
<tr
key={index}
className="hover:bg-gray-800 cursor-pointer"
onClick={() => {
if (track.youtubeId) {
onSelectSong(track);
}
}}
>
{!isMobile && <td className="py-2">{index + 1}</td>}
<td className="py-2">
<div className="flex items-center">
<img
src={track.youtubeId ? getYouTubeThumbnail(track.youtubeId) : "/placeholder.svg"}
alt="Video thumbnail"
className="w-10 h-10 mr-4 object-cover rounded-md"
/>
<div>
<p className="font-medium">{track.title}</p>
<p className="text-sm text-gray-400">{track.artist}</p>
</div>
</div>
</td>
{!isMobile && (
<td className="py-2 text-sm text-gray-400">
{track.album}
</td>
)}
{!isMobile && (
<td className="py-2 text-sm text-gray-400">
{track.added}
</td>
)}
{!isMobile && (
<td className="py-2 text-sm text-gray-400">
{track.duration ? formatTime(track.duration) : "--:--"}
</td>
)}
</tr>
))}
</tbody>
</table>
);
};
export default SongList;
f. Player.tsx
Controles de reproducción y barra de reproducción.
// components/Player.tsx
import React from "react";
import {
Play,
Pause,
SkipBack,
SkipForward,
Shuffle,
Repeat,
Volume1,
Volume2,
VolumeX,
Maximize2,
} from "lucide-react";
import { Button } from "./ui/button";
interface PlayerProps {
currentSong: Song;
isPlaying: boolean;
onPlayPause: () => void;
onNext: () => void;
onPrevious: () => void;
onShuffle?: () => void;
onRepeat?: () => void;
currentTime: number;
duration: number;
onSeek: (time: number) => void;
volume: number;
onVolumeChange: (volume: number) => void;
toggleMute: () => void;
isMobile: boolean;
}
const Player: React.FC<PlayerProps> = ({
currentSong,
isPlaying,
onPlayPause,
onNext,
onPrevious,
onShuffle,
onRepeat,
currentTime,
duration,
onSeek,
volume,
onVolumeChange,
toggleMute,
isMobile,
}) => {
const formatTime = (seconds: number): string => {
const minutes = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
const minutesStr = minutes < 10 ? `0${minutes}` : `${minutes}`;
const secondsStr = secs < 10 ? `0${secs}` : `${secs}`;
return `${minutesStr}:${secondsStr}`;
};
return (
<>
{/* Now Playing Bar para móviles */}
{isMobile && (
<div className="bg-gray-900 p-2 fixed bottom-0 left-0 right-0 z-50">
<div className="flex items-center justify-between">
<div className="flex items-center space-x-2 flex-grow">
<img
src={currentSong.youtubeId ? `https://img.youtube.com/vi/${currentSong.youtubeId}/hqdefault.jpg` : "/placeholder.svg"}
alt="Now playing cover"
className="w-12 h-12 rounded"
/>
<div>
<p className="font-medium">{currentSong.title}</p>
<p className="text-sm text-gray-400">{currentSong.artist}</p>
</div>
</div>
<div className="flex items-center space-x-4">
<Button
variant="ghost"
size="icon"
className="text-white"
onClick={onPlayPause}
aria-label={isPlaying ? "Pausar" : "Reproducir"}
>
{isPlaying ? (
<Pause className="h-6 w-6" fill="currentColor" />
) : (
<Play className="h-6 w-6" fill="currentColor" />
)}
</Button>
</div>
</div>
</div>
)}
{/* Barra de reproducción para pantallas grandes */}
{!isMobile && (
<div
className="flex flex-col lg:flex-row items-center justify-between p-4 bg-gray-900 border-t border-gray-800 fixed bottom-0 left-0 right-0"
>
{/* Información de la canción actual */}
<div className="flex items-center mb-4 lg:mb-0 w-full lg:w-1/3 justify-center lg:justify-start">
<img
src={currentSong.youtubeId ? `https://img.youtube.com/vi/${currentSong.youtubeId}/hqdefault.jpg` : "/placeholder.svg"}
alt="Album cover"
className="w-10 h-10 mr-4 object-cover rounded-md"
/>
<div>
<p className="font-medium">{currentSong.title}</p>
<p className="text-sm text-gray-400">{currentSong.artist}</p>
</div>
</div>
{/* Controles de reproducción y progreso */}
<div className="flex flex-col items-center w-full lg:w-1/3">
<div className="flex items-center space-x-4 mb-2">
<Button
variant="ghost"
size="icon"
className="text-gray-400 hover:text-white"
aria-label="Shuffle"
onClick={onShuffle}
>
<Shuffle className="w-5 h-5" />
</Button>
<Button
variant="ghost"
size="icon"
className="text-gray-400 hover:text-white"
aria-label="Anterior"
onClick={onPrevious}
>
<SkipBack className="w-5 h-5" />
</Button>
<Button
size="icon"
className="rounded-full bg-white hover:bg-gray-200"
onClick={onPlayPause}
aria-label={isPlaying ? "Pausar" : "Reproducir"}
>
{isPlaying ? (
<Pause className="w-6 h-6 text-black" />
) : (
<Play className="w-6 h-6 text-black" />
)}
</Button>
<Button
variant="ghost"
size="icon"
className="text-gray-400 hover:text-white"
aria-label="Siguiente"
onClick={onNext}
>
<SkipForward className="w-5 h-5" />
</Button>
<Button
variant="ghost"
size="icon"
className="text-gray-400 hover:text-white"
aria-label="Repetir"
onClick={onRepeat}
>
<Repeat className="w-5 h-5" />
</Button>
</div>
<div className="flex items-center w-full space-x-2">
<span className="text-xs text-gray-400">
{formatTime(currentTime)}
</span>
<input
type="range"
min={0}
max={duration}
value={currentTime}
onChange={(e) => onSeek(Number(e.target.value))}
className="flex-1 h-1 bg-gray-600 rounded-full cursor-pointer appearance-none focus:outline-none"
/>
<span className="text-xs text-gray-400">
{formatTime(duration)}
</span>
</div>
</div>
{/* Controles de volumen y pantalla completa */}
<div className="flex items-center justify-end w-full lg:w-1/3 mt-4 lg:mt-0">
<Button
variant="ghost"
size="icon"
className="text-gray-400 hover:text-white mr-2"
onClick={toggleMute}
aria-label={volume === 0 ? "Desmutear" : "Mute"}
>
{volume === 0 ? (
<VolumeX className="w-5 h-5" />
) : volume <= 50 ? (
<Volume1 className="w-5 h-5" />
) : (
<Volume2 className="w-5 h-5" />
)}
</Button>
<input
type="range"
min={0}
max={100}
value={volume}
onChange={(e) => onVolumeChange(Number(e.target.value))}
className="w-24 h-1 bg-gray-600 rounded-full cursor-pointer appearance-none focus:outline-none"
/>
<Button
variant="ghost"
size="icon"
className="text-gray-400 hover:text-white ml-2"
aria-label="Pantalla completa"
>
<Maximize2 className="w-5 h-5" />
</Button>
</div>
</div>
)}
</>
);
};
export default Player;
g. MainContent.tsx
Contiene la información de la playlist y la lista de canciones.
// components/MainContent.tsx
import React from "react";
import PlaylistInfo from "./PlaylistInfo";
import SongList from "./SongList";
interface MainContentProps {
playlist: Playlist;
songs: Song[];
isMobile: boolean;
onSelectSong: (song: Song) => void;
}
const MainContent: React.FC<MainContentProps> = ({
playlist,
songs,
isMobile,
onSelectSong,
}) => {
return (
<div className="flex flex-col p-6 overflow-y-auto bg-gradient-to-b from-red-900 to-gray-900">
<PlaylistInfo playlist={playlist} isMobile={isMobile} />
<SongList songs={songs} isMobile={isMobile} onSelectSong={onSelectSong} />
</div>
);
};
export default MainContent;
3. Refactorizar el Componente Principal
Después de crear los componentes individuales, el componente principal SpotifyClone se simplificará considerablemente. Además, podemos crear un hook personalizado para manejar la lógica del reproductor, mejorando aún más la legibilidad.
a. Crear un Hook Personalizado para el Reproductor
// hooks/useYouTubePlayer.ts
import { useRef, useEffect } from "react";
import YouTubePlayer from "react-youtube";
interface UseYouTubePlayerProps {
videoId: string;
isPlaying: boolean;
volume: number;
onEnd: () => void;
onStateChange?: (event: any) => void;
setDuration: (duration: number) => void;
setCurrentTime: (time: number) => void;
}
const useYouTubePlayer = ({
videoId,
isPlaying,
volume,
onEnd,
onStateChange,
setDuration,
setCurrentTime,
}: UseYouTubePlayerProps) => {
const playerRef = useRef<YouTubePlayer | null>(null);
const onReady = (event: any) => {
playerRef.current = event.target;
setDuration(event.target.getDuration());
event.target.setVolume(volume);
if (isPlaying) {
event.target.playVideo();
}
};
useEffect(() => {
if (playerRef.current) {
if (isPlaying) {
playerRef.current.playVideo();
} else {
playerRef.current.pauseVideo();
}
}
}, [isPlaying]);
useEffect(() => {
if (playerRef.current) {
playerRef.current.setVolume(volume);
}
}, [volume]);
useEffect(() => {
let intervalId: NodeJS.Timeout | null = null;
if (playerRef.current && isPlaying) {
intervalId = setInterval(() => {
const current = playerRef.current!.getCurrentTime();
const dura = playerRef.current!.getDuration();
setCurrentTime(current);
setDuration(dura);
}, 1000);
}
return () => {
if (intervalId) clearInterval(intervalId);
};
}, [isPlaying, setCurrentTime, setDuration]);
return { onReady, playerRef };
};
export default useYouTubePlayer;
b. Refactorizar SpotifyClone
// SpotifyClone.tsx
import React, { useState, useEffect } from "react";
import Navbar from "./components/Navbar";
import Sidebar from "./components/Sidebar";
import MainContent from "./components/MainContent";
import Player from "./components/Player";
import YouTubePlayer from "./components/YouTubePlayer";
import useYouTubePlayer from "./hooks/useYouTubePlayer";
// ... (resto de tus imports)
const SpotifyClone = () => {
const [currentSong, setCurrentSong] = useState<Song | null>(null);
const [isPlaying, setIsPlaying] = useState<boolean>(false);
const [isSidebarOpen, setIsSidebarOpen] = useState<boolean>(true);
const [isMobile, setIsMobile] = useState<boolean>(window.innerWidth < 1024);
const [currentTime, setCurrentTime] = useState<number>(0);
const [duration, setDuration] = useState<number>(0);
const [volume, setVolume] = useState<number>(100);
useEffect(() => {
const handleResize = () => {
if (window.innerWidth < 1024) {
setIsMobile(true);
setIsSidebarOpen(false);
} else {
setIsMobile(false);
setIsSidebarOpen(true);
}
};
handleResize();
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
// Lógica para controlar la reproducción de canciones
const handleNextSong = () => {
if (!currentSong) return;
const currentIndex = songs.indexOf(currentSong);
const nextIndex = (currentIndex + 1) % songs.length;
const nextSong = songs[nextIndex];
setIsPlaying(false);
setCurrentSong(nextSong);
};
const handlePreviousSong = () => {
if (!currentSong) return;
const currentIndex = songs.indexOf(currentSong);
const previousIndex = (currentIndex - 1 + songs.length) % songs.length;
const previousSong = songs[previousIndex];
setIsPlaying(false);
setCurrentSong(previousSong);
};
const togglePlayPause = () => {
setIsPlaying(!isPlaying);
};
const toggleMute = () => {
if (volume > 0) {
setVolume(0);
} else {
setVolume(100);
}
};
const handleSelectSong = (song: Song) => {
setCurrentSong(song);
setIsPlaying(true);
};
return (
<div className="flex flex-col h-screen text-gray-300 bg-black">
{/* Renderizar el reproductor de YouTube solo si hay una canción seleccionada */}
{currentSong?.youtubeId && (
<YouTubePlayer
videoId={currentSong.youtubeId}
isPlaying={isPlaying}
onEnd={handleNextSong}
volume={volume}
setDuration={setDuration}
setCurrentTime={setCurrentTime}
/>
)}
{/* Navbar */}
<Navbar
isMobile={isMobile}
isSidebarOpen={isSidebarOpen}
toggleSidebar={() => setIsSidebarOpen(!isSidebarOpen)}
/>
{/* Layout Principal */}
<div className="flex flex-1 overflow-hidden">
{/* Sidebar */}
<Sidebar
isSidebarOpen={isSidebarOpen}
isMobile={isMobile}
closeSidebar={() => setIsSidebarOpen(false)}
/>
{/* Fondo transparente para cerrar la barra lateral en móviles */}
{isSidebarOpen && isMobile && (
<div
className="fixed inset-0 bg-black opacity-50 z-40 lg:hidden"
onClick={() => setIsSidebarOpen(false)}
></div>
)}
{/* Contenido Principal */}
<MainContent
playlist={playlist}
songs={songs}
isMobile={isMobile}
onSelectSong={handleSelectSong}
/>
</div>
{/* Player */}
{currentSong && (
<Player
currentSong={currentSong}
isPlaying={isPlaying}
onPlayPause={togglePlayPause}
onNext={handleNextSong}
onPrevious={handlePreviousSong}
currentTime={currentTime}
duration={duration}
onSeek={(time) => {
// Implementa la lógica para buscar
}}
volume={volume}
onVolumeChange={setVolume}
toggleMute={toggleMute}
isMobile={isMobile}
/>
)}
</div>
);
};
export default SpotifyClone;
4. Mejoras Adicionales
a. Uso de Contexto para el Reproductor
Si tu aplicación crecerá, considera usar React Context para manejar el estado del reproductor (canción actual, estado de reproducción, volumen, etc.). Esto evitará prop-drilling y facilitará el acceso al estado desde cualquier componente.
b. Memoización
Usa React.memo para componentes que no necesitan renderizarse nuevamente a menos que sus props cambien. Esto puede mejorar el rendimiento al evitar renders innecesarios.
// components/SongList.tsx
import React from "react";
const SongList: React.FC<SongListProps> = React.memo(({ songs, isMobile, onSelectSong }) => {
// ... código del componente
});
c. Validación de Props
Asegúrate de que todos los props necesarios se pasen correctamente y considera usar PropTypes o, si usas TypeScript, define las interfaces adecuadamente.
d. Optimización de Imágenes
Usa técnicas de optimización de imágenes como lazy loading para mejorar el rendimiento.
<img
src={track.youtubeId ? getYouTubeThumbnail(track.youtubeId) : "/placeholder.svg"}
alt="Video thumbnail"
className="w-10 h-10 mr-4 object-cover rounded-md"
loading="lazy"
/>
e. Externalizar las Constantes
Extrae las constantes reutilizables como la lista de canciones y la información de la playlist en archivos separados para una mejor organización.
// data/songs.ts
export interface Song {
title: string;
artist: string;
album: string;
added: string;
duration?: number;
youtubeId?: string;
}
export const songs: Song[] = [
{
title: "Las Piponas (Remix)",
artist: "Kris R., Blessed",
album: "Las Piponas (Remix)",
added: "hace 2 horas",
duration: 242,
youtubeId: "Dftj21lTUIA",
},
// Más canciones...
];
// data/playlist.ts
export const playlist = {
name: "Time Free",
description: "Relajao",
owner: "Johan Morales",
timesSaved: 8,
songsCount: 1253,
totalDuration: "72 h 6 min",
coverImage: "https://i.postimg.cc/y8KhsW1p/imagen-blessd.jpg",
};
f. Manejo de Estado Global con Contexto o una Biblioteca de Estado
Si consideras que el manejo del estado se vuelve complejo, podrías integrar una biblioteca como Redux o usar React Context para manejar el estado globalmente.
5. Conclusión
Refactorizar tu aplicación en componentes más pequeños mejora significativamente la mantenibilidad y la escalabilidad. Además, aplicar buenas prácticas como la memoización, el uso de hooks personalizados y la externalización de datos ayuda a mantener el código limpio y eficiente.
Implementando estos cambios, tu código inicial:
import React, { useState, useEffect, useRef } from "react";
// ... otros imports
Se transforma en una estructura modularizada donde cada componente se encarga de una responsabilidad específica, facilitando su mantenimiento y ampliación futura.
Si tienes alguna pregunta adicional o necesitas más ayuda con alguna parte específica, ¡no dudes en decírmelo!