TIL / React > useEffect() Hook

Agnes Shin·2022년 2월 21일
0
post-custom-banner

What is useEffect?
side effect

Why do you use useEffect() hook?

import React, { useState, useEffect } from 'react'
 
export  default function App() {
	const [resouceType, setResourceType] = useState('posts
    const [items. setItems] = useState([]  )
    console.log('render');
   	
    // useEffect(() => {
    	console.log('resouce type changed')
    
     
      useEffect() => {
    	fetch('https://jsonplaceholder.typicode.com/${resourcType}')
    		.then(response => response.json())
            //.then(json => console.log(json))
            .then(json => setItems(json))
    }, [resouceType]) 
    
 		console.log(setItems);
         
    })
    
   return (
   <>
   	<div>
		<button onClick={() => setResourceType('posts')}>Posts</button>
        <button onClick={() => setResourceType('users')}>Users</button>
        <button onClick={() => setResourceType('comments')}>Comments</button>
    </div>
    <h1>{resouceType}</h1>
    {items.map(item => {
		return <pre>{JSON.stringify(item)} </pre>
    }))
  </>
 )
}
 import React, { useState, useEffect } from 'react'
 
 export default function App() {
 	const [windowWidth, setWindowWidth] = useState(window.innerWidth)
    
    const handleResize = () => {
    	setwindowWidth(window.innerWidth)
    }
    
    useEffect(() => {
    	window.addEventListener('resize', handleResize)
        
        return () => {
        	window.removeEventListener('resize', handleReize) // this is returned to remove this event listner
        }
    }, [])
    
    return (
    <div>{windowWidth}</div>
 }
import React, { useState, useEffect } from 'react'
 
export  default function App() {
	const [resouceType, setResourceType] = useState('posts
    const [items. setItems] = useState([]  )
    console.log('render');
 
      useEffect() => {
    	console.log('resouce changed')
        
        return () => {
       		console.log('return from resourc change')
        }
    }, [resouceType]) 
    
    
 		console.log(setItems);
         
    })
    
   return (
   <>
   	<div>
		<button onClick={() => setResourceType('posts')}>Posts</button>
        <button onClick={() => setResourceType('users')}>Users</button>
        <button onClick={() => setResourceType('comments')}>Comments</button>
    </div>
    <h1>{resouceType}</h1>
    {items.map(item => {
		return <pre>{JSON.stringify(item)} </pre>
    }))
  </>
 )
}
profile
30기 신윤숙 / FE
post-custom-banner

0개의 댓글