简体   繁体   中英

React use useMemo-hook after useEffect-hook

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!

useEffect runs after your component renders, by that time your state is still an empty array. if you want to use memo hook, you should pass its dependencies in order to them to reflect correctly given your users state:

const childRefs = useMemo<any>(
    () =>
      Array(users.length)
        .fill(0)
        .map((i) => React.createRef()),
    [users] //add dependencies
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM