I need access to HTML-elements to interact with them later on (like adding animations on button-click). For this I want to use the useMemo-hook. My setup is as follows:
I'm getting data from firebase via useEffect:
useEffect(() => {
const unsubscribe = database.collection("users").onSnapshot((snapshot) => {
snapshot.forEach((doc) => {
...
}, []);
and storing it in a useState-hook:
const [users, setUsers] = useState([] as any[]);
In this case, with getting asynchronous data from a database first and storing it in useState, it's not possible to initialize the useMemo-hook with values, because the data isn’t loaded yet (as both hooks fire at the same time I guess). So the childRef-array is always an empty array.
The useMemo-hook looks like this:
const childRefs = useMemo<any>(
() =>
Array(users.length)
.fill(0)
.map((i) => React.createRef()),
[]
);
... and the created childRefs should be used as ref in the render-function as follows:
{users.map((user, index) => (
<div key={user.id}>
<div ref={childRefs[index]}>{user.username}</div>
</div>
))}
Any ideas how I can manage to run useMemo after useEffect to get the childRefs-array filled? I already thought about something like putting a short timeout before executing useMemo, but I don’t know how to do this and it's not a proper solution.
Thanks a lot for any advice!