DEV Community

Hyunjin Cho
Hyunjin Cho

Posted on

2 1

March 31th, 2022

React Hook - useEffect

can be used in component life cycle.. (mount, unmount, update...)
After the page is rendering, the useEffect must be run once.
When the dependencies that set in the array, the useEffect is run.

  1. useEffect(()=>{})
  2. useEffect(()=>{}, [])
  3. useEffect(()=>{}, [dependency])

1 -> basic, but not used usually. no dependency, loading anytime
2 -> After the page rendering, the useEffect has be used only once.
3 -> After the page rendering, the useEffect has run one time and run again when the dependency (value in the array) is changed.

What to do in useEffect

useEffect(() => {
console.log('mount')
return () => {
console.log('unmount)}
, []}

1st param = function
2nd param = dependency array

return part is clean up part

when mount,

  • set props to state
  • request API
  • use library
  • iteration with setInterval
  • work with setTimeOut

when unmount,

clean the registered work(clearInterval, clearTimeout)
clean the library instance

When not setting props that are used in useEffect to dependency array, the function in useEffect cannot point out the latest props.

React Hook - useCallback

reuse the already created function

When defining the function like the before, the function is created every time the rendering.

const onRemove = id => {
setUsers(users.filter(user => user.id !== id));
};

const onRemove = useCallback(id =>{
setUsers(users.filter(user => user.id !== id));
}, [users])

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more