Home > Mobile >  Can I run a function after useMemo return is on the screen
Can I run a function after useMemo return is on the screen

Time:10-21

I'd like to get some kind of call back once memoizedTodos are displayed on the screen.

or execute handleOpen function once memoizedTodos are displayed on the screen.

Right now what I'm displaying on the screen is just the text. but you could imagine that this useMemo returns thousands of texts and images so it will take a while for those to be on the screen.

What I want to do here is run the handleOpen function after memoizedTodos returns are displayed like I can see all the todos visibly on the screen.

Are there any way that I can do this?

I thought I could use async/await to do this? or what would it be the best way to do this?

import React, { useMemo } from "react";
import "./styles.css";

export default function App() {

  const handleOpen = () => {
    console.log("this is running");
  };

   const memoizedTodos = useMemo(() => {
    return [...Array(n)].map((e, i) => <li key={i}>This is so many data</li>);
  }, []);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <>{memoizedTodos}</>
    </div>
  );
}


CodePudding user response:

I'd like to get some kind of call back once memoizedTodos are displayed on the screen.

The callback you are looking for is actually useEffect with empty dependency array.

or execute handleOpen function once memoizedTodos are displayed on the screen.

useEffect will be invoked after the render, when memoizedTodos are already rendered.

The order: useMemo -> render -> useEffect

So all you actually need is:

useEffect(() => {
  console.log("this is running");
}, []);

CodePudding user response:

You can use useEffect with memoizedTodos as dependency like this

useEffect(()=>{
    console.log('this is a callbak')
  },[memoizedTodos])
  • every time your memoizedTodos change the useEffect will be executed
  • also the useEffect is execute after the render
  • render is produced by memoized change (you have your callback)
  • Related