Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

255
Views
React State Storing & Outputting Duplicate Values every re-render

Whenever my page loads I execute the useEffect() function below to retrieve data from firebase and set it to my local state calendarList but every time the page renders it makes a duplicate of the data and pushes is to the state so I have twice as many objects stored. How can I prevent this from happening?

STATE

const [calendarList, setCalendarList] = useState([]);

USE EFFECT - executes on page load

useEffect(() => {
    db.collection("users")
      .doc(userId)
      .collection("calendars")
      .onSnapshot((snapshot) => {
        const calendarArray = [];

        snapshot.forEach((doc) => {
         
          calendarArray.push(doc.data()); push all doc obejects to calendar array
        });
       

        setCalendarList(calendarArray); //set state 
      });
  }, []);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

you can create a custom hook, perhaps.

create a new file and call it as you wish, but gurus out there says it must have to start with use

//useCalendar.js

import {useState, useEffect} from "react"; 

const useCalendar = (userId) => {
  const [calendarList, setCalendarList] = useState([]);

    const addItem = (item) => {
      // use this to add mow items
    };

    const cleanList = () => {
       setCalendarList([]);
    }

    const getItemById = (id) => {
      // use this to get an item
    };

  useEffect(()=> {
    db.collection("users")
      .doc(userId)
      .collection("calendars")
      .onSnapshot(snapshot => {
        const calendarArray =  snapshot && snapshot.map(doc => doc.data());
       
        setCalendarList(calendarArray || []);
      });
  },[userId, list]);

  return {
    calendarList,
    addItem,
    cleanList,
    getItemById
   };

}

export default useCalendar;

now at yow component use it like

const component = () => {
  const { calendarList, addItem, cleanList, getItemById } = useCalendar(userId);
...

}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!