'useEffect Doesnt render the page Automatically in React JS

I am trying to fetch the data from firebase using useEffect in React JS, But my problem is its not updating / rendering the page automatically when Any changes in database occurs.

I Tried

const [users,setUsers]=useState([]);

const usersCollectionRef=collection(db,"customers");

useEffect(()=>{
        const getUsers=async ()=>{
            const data=await getDocs(usersCollectionRef);
            setUsers(data.docs.map((doc)=>({...doc.data(),id:doc.id})))
        };
        getUsers();
        console.log(users)
    },[])

and here returning the data

return (
    <div className="App">
        {users.map((user)=>{
            return <h1 key={user.id}>{user.id}</h1>
        })}
    </div>
  )

Please help me with this



Solution 1:[1]

Just use onSnapshot. It will update on every changes in collection. So, Answer

useEffect(() => {
        onSnapshot(usersCollectionRef, (snapshot) =>
            setUsers(snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id })))
        )
    }, [])

Solution 2:[2]

Your useEffect will run only once because your dependency list its empty.

If you want to triger this useEffect you will add some condition to the dependency list.

More on that : https://reactjs.org/docs/hooks-effect.html

Solution 3:[3]

In the above code useEffect will execute only once because of empty dependency array. You can remove dependency array to execute repeatedly or you can pass variables to execute whenever the data in the variable changes as below:

useEffect(()=>{
    Code
 })

Or

useEffect(()=>{
    Code
},[Variables])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vivek Raj Singh
Solution 2 yanir midler
Solution 3 yanir midler