DEV Community

Hyunjin Cho
Hyunjin Cho

Posted on

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])

Top comments (0)