React

Tue, 03 May 2022 11:06:52 GMT

 Properties

Key Value
Identifier react
Name React
Type Topic
Creation timestamp Tue, 03 May 2022 11:06:52 GMT
Modification timestamp Tue, 03 May 2022 11:06:52 GMT


Notes
Mon, 28 Aug 2023 10:55:55 GMT
React useEffect hook to fetch data

The useEffect hooks syntax looks pretty straight forward with a fetch request wrapped inside the hook and the other argument can have three possible inputs, nothing, empty array and array containing state, props or both.

The useEffect hook always run the callback function that is inside of it after the component has been rendered and here the fetch request gets initiated after the component is rendered and the data is fetched and set to the info state and after that the question is whether the useEffect needs to be run again after once it has been executed which depends on the dependency array:

No Dependency Array

useEffect runs the callback function every time after the component it is in gets rendered. In simple words, the callback function is dependent on everything (state, props of that component).

useEffect(() => {
     fetch("https://jsonplaceholder.typicode.com/todos/1")
       .then(res => res.json())
       .then(data => setState(data))
   })

Empty Dependency Array ([])

useEffect runs the callback function only one time after the component gets rendered first time. In simple words, the callback function is dependent on nothing.

useEffect(() => {
  fetch("https://jsonplaceholder.typicode.com/todos/1")
       .then(res => res.json())
       .then(data => setState(data))
}, [])

Filled Dependency Array ([state, props])

useEffect runs the callback function every time the state/props that is inside the dependency array updates. In simple words, the callback function is dependent on particular states and props.

useEffect(() => {
  fetch("https://jsonplaceholder.typicode.com/todos/1")
       .then(res => res.json())
       .then(data => setState(data))
}, [state, props])


Back to top



 Context