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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay