Problem
My component renders every second instead of only rendering if the state passed into setCurrentlyPlaying() is different. How can I fix this behavior?
Background
I would like to check an API every 1 second. Aside from the first render, I only want my component to rerender when the incomingSong differs from the currentlyPlayingSong. I'm banking on the State hook's ability to only trigger a rerender if the passed in state is different than the previous based on the Object.is comparison algorithm. Even if I only return(<div></div>
); in my component it continues to render every 1 second, so it seems like the problem stems from this logic. I test this by playing NOTHING on my Spotify so it always goes into the first if
statement and it still rerenders every second (prints the console.log("RENDERED") statement).
const [currentlyPlayingSong, setCurrentlyPlayingSong] = useState({ type: 'Now Playing', name: 'No Song Playing', artists: [], imageUrl: ''});
console.log("RENDERED")
useEffect(() => {
console.log("initial effect including updateSongs");
const updateSongs = async () => {
const result = await getCurrentlyPlaying();
var incomingSong = {};
// no song is playing
if(result.data === "") {
incomingSong = { type: 'Now Playing', name: 'No Song Playing', artists: [], imageUrl: ''};
}
// some song is playing
else {
var songJSONPath = result.data.item;
incomingSong = {
type: 'Now Playing',
name: songJSONPath.name,
id: songJSONPath.id,
artists: songJSONPath.artists.map(artist => artist.name + " "),
imageUrl: songJSONPath.album.images[songJSONPath.album.images.length - 2].url,
};
}
// console.log("currentlyPlayingSong: ", currentlyPlayingSong)
// console.log("incomingSong: ", incomingSong);
// this line!!!!
setCurrentlyPlayingSong(incomingSong);
}
updateSongs();
const timer = setInterval(updateSongs, 1000);
return () => clearInterval(timer);
},[]);