31
loading...
This website collects cookies to deliver better user experience
Prior to React v16.8
, we can only enable a component
to react to state changes using lifecycle methods.
useEffect(() => { //(1) declaration
// (2)effect
return () => {
// (3)cleanup
}
}, /* (4)dependency array */)
React.useEffect
or useEffect
effect
is the function that will be called when the component is mounted
OR when the dependency array changes.cleanup
is the function that will be called when the effect "unmounted".dependency array
is the array of values that will be passed to the effect
function.
function App() {
const [count, setCount] = useState(0)
useEffect(() => {
if (count < 10) {
const interval = setInterval(() => {
setCount(prev => prev + 1)
}, 1000)
// cleanup function
return () => clearInterval(interval)
}
}, [count])
// Render the component
}
function App() {
const [data, setData] = useState([])
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(res => res.json())
.then(data => setData(data))
}, [])
// Render the component
}
function App() {
const [data, setData] = React.useState()
const [error, setError] = React.useState()
const [isLoading, setIsLoading] = React.useState(false)
React.useEffect(() => {
setIsLoading(true)
fetchData()
.then(data => {
setError(null)
setData(data)
})
.catch(data => {
// handle error case anyway you want
setError(data)
setData(null)
})
.finally(() => setIsLoading(false))
}, [])
// Render the component
}
function App() {
const [data, setData] = React.useState()
const [error, setError] = React.useState()
const [isLoading, setIsLoading] = React.useState(false)
React.useEffect(() => {
// yeah, this is weird
(async () => {
try {
setIsLoading(true)
const data = await fetchData()
setError(null)
setData(data)
} catch(e) {
// handle error case anyway you want
setError(e)
setData(null)
}
setIsLoading(false)
})()
}, [])
// Render the component
}
function App({ name }) {
const [value, setValue] = useState(() => localStorage.getItem(name))
useEffect(() => {
localStorage.setItem(name, value)
}, [name, value])
// Ignore old keys for now
// Render the component
}
Check this blog on how to convert a class lifecycle methods to useEffect
hooks
useEffect
can only be used in functional componentsuseEffect
declarations are important.useEffect
in a custom hook is a great way to promote side effect reusability. I will discuss this in another blog.useEffect
is much more powerful and flexible, making it an ideal choice when managing a side-effect.