ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • useEffect
    개발/react 2020. 12. 21. 20:27

    리액트의 useEffect 라이브러리는 컴포넌트나 state에 변화가 생길 때 호출되는 함수다. 두개의 인자를 받는데 첫째 인자는 변경시 호출할 콜백함수고 두번째 인자는 상태를 변경을 감지할 state를 설정한다.  state를 별도로 설정하지 않으면 componentDidUpdate, componentDidMount랑 동일한 역할을 하게 된다. 

     

    const NoteApp = () => {
      
      const [notes, setNotes] = useState([])
      const [title, setTitle] = useState('')
      const [body, setBody] = useState('')
    
      useEffect(() => {
        console.log('load data')
        const notesData = JSON.parse(localStorage.getItem('notes'))
        if (notesData) {
          setNotes(notesData)
        }
      }, [])
    
      useEffect(() => {
        console.log('update notes')
        const toJson = JSON.stringify(notes)
        localStorage.setItem('notes', toJson)
      }, [notes])
    
      useEffect(() => {
        console.log('useEffect called')
      })

     

    위와 같이 여러개의 useEffect 함수를 둘 수 있다. 첫번째 useEffect에서는 두번째 인자에 빈 배열을 넣었는데 이러면 최초 한번만 호출되게 된다. componentDidMount 콜백과 기능이 유사하다. 두번째 useEffect 함수에서는 notes 상태 값을 인자로 두었다. notes 상태의 값이 변경될 때마다 함수가 호출된다. 세번째 useEffect 함수는 전달인자를 따로 넣지 않아서 내부에 어떤 state가 바뀌더라도 새롭게 호출된다. 

     

     

    '개발 > react' 카테고리의 다른 글

    useContext  (0) 2020.12.22
    useReducer  (0) 2020.12.22
    useState  (0) 2020.12.21
    connect  (0) 2020.12.20
    react router  (0) 2020.12.17

    댓글

Designed by Tistory.