I'm learning react for past few days and while using useEffect hook i'm getting infite loop over setting my state variable.
Can anyone tell me what's going on and how to overcome this
Here's my code
import React, { useState, useEffect } from "react";
import axios from "axios";
const TodoEntry = () => {
const [todos, setTodos] = useState('');
useEffect(() => {
axios.get('http://localhost:5000/api/todos')
.then(res => { setTodos(res.data); console.log(todos) })
.catch(err => console.log(err))
},[todos]);
return (
<div>
<h1>Todo App</h1>
</div>
);
};
export default TodoEntry;
Couple of problems in your code:
Since getTodos function is a dependency of useEffect hook, every time state updates, new getTodos function is created which then triggers the useEffect hook.
You don't need to chain then function when using async-await syntax. You can just await the result of axios.get(...).
To fix the first problem of infinite loop, use one of the following options:
Wrap the getTodos function in useCallback hook. For details, see useCallback.
Since, getTodos function calls displayTodos, you will need to wrap it in useCallback hook and add displayTodos in the dependency array of useCallback hook that wraps getTodos function. In my opinion, it is better to just remove the displayTodos function and update the state inside getTodos function
const getTodos = useCallback(async () => {
try {
const res = await axios.get('http://localhost:5000/api/todos')
setTodos(res.data);
} catch(err) {
console.log(err);
}
}, [setTodos]);
Demo
Put the code inside getTodos inside useEffect hook and remove the getTodos function.
useEffect(() => {
axios.get("http://localhost:5000/api/todos")
.then(res => setTodos(res.data))
.catch(err => console.log(err));
}, [setTodos]);
Demo
This is because the dependency list for your useEffect call is a function. You probably meant to add the todos data itself.
useEffect(() => {
getTodos();
},[todos]);
Related
I have a simple async function that I want to be called when a page loads which fetches data and updates my context.
import { useContext } from 'react'
import { ContentSlotsContext } from '../commerce-api/contexts'
export default async function getSlots() {
const { slots, setSlots } = useContext(ContentSlotsContext)
const response = await fetch('https://jsonplaceholder.typicode.com/todos');
const data = await response.json();
setSlots(data);
}
I'm trying to call it like this:
useEffect(() => {
getSlots()
})
slots and setSlots are a setState the context is initialised with.
But it's not being called. When I call it outside of useEffect it works but infinitely loops due to constantly re-rendering.
The problem is that you're calling useContext from a function that is not a react function component or a custom hook (see the rules of hooks). There's a useful ESLint plugin eslint-plugin-react-hooks that will warn against this.
To fix the issue, you can instead pass setSlots as a parameter to getSlots:
export default async function getSlots(setSlots) {
const response = await fetch('https://jsonplaceholder.typicode.com/todos');
const data = await response.json();
setSlots(data);
}
and call useContext before useEffect, at the top level of your function component (also a rule of hooks), with an empty dependencies array as the second argument, so the effect only fires once (see the note in the useEffect docs):
..
const { setSlots } = useContext(ContentSlotsContext);
useEffect(() => {
getSlots(setSlots);
}, []);
..
Should I ignore 'React Hook useEffect has a missing dependency' warning?
Usually when I am getting data from an API this is what I do:
const Component = () => {
const [data,setData] = useState([]);
const getData = () => {
//Getting data and set data code...
}
useEffect(()=>{
getData();
},[]);
}
and recently I am trying out use redux to do the same thing(getting data from API) and I got this 'React Hook useEffect has a missing dependency' warning...
action:
import {GET_POSTS} from './types';
const getPosts = () => (dispatch) => {
const url = 'https://jsonplaceholder.typicode.com/posts';
fetch(url)
.then(res => res.json())
.then(data => {
dispatch({
type: GET_POSTS,
payload: data
});
});
}
export default getPosts;
reducer:
import {GET_POSTS} from '../actions/types';
const initialState = {
posts: []
}
const postsReducer = (state = initialState, action) => {
switch(action.type){
case GET_POSTS:
return {
...state,
posts: action.payload
}
default:
return state;
}
}
export default postsReducer;
app.js:
import React, {useEffect} from 'react';
import {connect} from 'react-redux';
import Hello from './components/Hello';
import getPost from './actions/postsAction';
import './App.css';
const App = ({getPost, dispatch}) => {
useEffect(() => {
getPost();
},[]);
return (
<div className='App'>
<Hello/>
</div>
);
};
const mapdispatchtoprops = (dispatch) => ({
dispatch,
getPost: () => {
dispatch(getPost());
}
});
export default connect(null, mapdispatchtoprops)(App);
Is there a way to fix this problem, I have tried to put dispatch inside the useEffect array but the warning still shows, like this:
useEffect(() => {
getPost();
},[dispatch]);
This is the full warning: React Hook useEffect has a missing dependency: 'getPost'. Either include it or remove the dependency array react-hooks/exhaustive-deps
Tried to remove the useEffect array but I'll get infinite loop, it'll just keeps getting the data from the api(I only need it to run once).
Should I ignore the warning? if not, whats the best practice way to handle this problem?
I never got this kind of warning before when I left the useEffect array empty but got it recently, why?
The error message is telling you what you to do. Just add getData to the dependencies array like so: [dispatch, getData]. Anything external you reference within your useEffect (like a function) should be part of the dependency list so it can trigger the effect whenever the value changes. In your case it likely won't, but React is warning you just to be safe. Hope that helps!
You may want to start thinking from a different perspective. You are apparently trying to do side effect of loading data after component got rendered. So just inject your data via redux or propagation props from parent and remove array altogether. I.e.
const Component = ({posts}) => {
const getData = () => {
//Getting data and set data code...
}
useEffect(() => {
if (!posts) {
getData();
}
});
....
}
Your posts will be loaded once and useEffect's function should only care about posts is there or not.
Why is my useEffect react function running on every page load although giving it a second value array with a query variable?
useEffect( () => {
getRecipes();
}, [query]);
Shouldn't it only run when the query state variable changes? I have nothing else using the getRecipes function except of the useEffect function.
import React, {useEffect, useState} from 'react';
import './App.css';
import Recipes from './components/Recipes/Recipes';
const App = () => {
// Constants
const APP_ID = '111';
const APP_KEY = '111';
const [recipes, setRecipes] = useState([]);
const [search, setSearch] = useState('');
const [query, setQuery] = useState('');
const [showRecipesList, setShowRecipesList] = useState(false);
// Lets
let recipesList = null;
// Functions
useEffect( () => {
getRecipes();
}, [query]);
// Get the recipie list by variables
const getRecipes = async () => {
const response = await fetch(`https://api.edamam.com/search?q=${query}&app_id=${APP_ID}&app_key=${APP_KEY}&from=0&to=3&calories=591-722&health=alcohol-free`);
const data = await response.json();
console.log(data.hits);
setRecipes(data.hits);
}
// Update the search constant
const updateSearch = e => {
console.log(e.target.value);
setSearch(e.target.value);
}
const runQuery = e => {
e.preventDefault();
setQuery(search);
}
// List recipes if ready
if (recipes.length) {
console.log(recipes.length);
recipesList = <Recipes recipesList={recipes} />
}
return (
<div className="App">
<form className='search-app' onSubmit={ runQuery }>
<input
type='text'
className='search-bar'
onChange={ updateSearch }
value={search}/>
<button
type='submit'
className='search-btn' > Search </button>
</form>
<div className='recipesList'>
{recipesList}
</div>
</div>
);
}
export default App;
Following this: https://www.youtube.com/watch?v=U9T6YkEDkMo
A useEffect is the equivalent of componentDidMount, so it will run once when the component mounts, and then only re-run when one of the dependencies defined in the dependency array changes.
If you want to call getRecipes() only when the query dependency has a value, you can call it in a conditional like so:
useEffect(() => {
if(query) {
getRecipes()
}
}, [query])
Also, as your useEffect is calling a function (getRecipes) that is declared outside the use effect but inside the component, you should either move the function declaration to be inside the useEffect and add the appropriate dependencies, or wrap your function in a useCallback and add the function as a dependency of the useEffect.
See the React docs for information on why this is important.
UseEffect hook work equivalent of componentDidMount, componentDidUpdate, and componentWillUnmount combined React class component lifecycles.but there is a different in time of acting in DOM.componentDidMount and useEffect run after the mount. However useEffect runs after the paint has been committed to the screen as opposed to before. This means you would get a flicker if you needed to read from the DOM, then synchronously set state to make new UI.useLayoutEffect was designed to have the same timing as componentDidMount. So useLayoutEffect(fn, []) is a much closer match to componentDidMount() than useEffect(fn, []) -- at least from a timing standpoint.
Does that mean we should be using useLayoutEffect instead?
Probably not.
If you do want to avoid that flicker by synchronously setting state, then use useLayoutEffect. But since those are rare cases, you'll want to use useEffect most of the time.
My folder structure:
|--App
|--Components
|--PageA.js
|--PageB.js
|--PageC.js
|--common-effects
|--useFetching.js
I am refactoring my code to fetch data from API, using react hooks.
I want to dispatch an action from useEffect in useFetching.js that is intercepted by saga middleware. The action should be dispatched only when the components(PageA, PageB, PageC) mount.
I am using redux, react-redux and redux-saga.
PageA.js:
function(props) {
useFetching(actionParams)
//....//
}
Similar code for PageB and PageC components.
I have abstracted the reusable code to fetch data in useFetching Custom hook.
useFetching.js
const useFetching = actionArgs => {
useEffect( () => {
store.dispatch(action(actionArgs)); // does not work
})
}
I don't know how to access redux dispatch in useFetching. I tried it with useReducer effect, but the sagas missed the action.
Version using react-redux hooks:
You can even cut out the connect function completely by using useDispatch from react-redux:
export default function MyComponent() {
useFetching(fetchSomething);
return <div>Doing some fetching!</div>
}
with your custom hook
import { useDispatch } from 'react-redux';
const useFetching = (someFetchActionCreator) => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(someFetchActionCreator());
}, [])
}
Edit: removed dispatch from custom hook as suggested by #yonga-springfield
Note: React guarantees that dispatch function identity is stable and won’t change on re-renders. This is why it’s safe to omit from the useEffect or useCallback dependency list.
You would need to pass either bound action creators or a reference to dispatch to your hook. These would come from a connected component, same as you would normally use React-Redux:
function MyComponent(props) {
useFetching(props.fetchSomething);
return <div>Doing some fetching!</div>
}
const mapDispatch = {
fetchSomething
};
export default connect(null, mapDispatch)(MyComponent);
The hook should then call the bound action creator in the effect, which will dispatch the action accordingly.
Also, note that your current hook will re-run the effect every time the component is re-rendered, rather than just the first time. You'd need to modify the hook like this:
const useFetching = someFetchActionCreator => {
useEffect( () => {
someFetchActionCreator();
}, [])
}
This is just to bring some optimization to #Alex Hans' answer.
As per the documentation here. A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks.
With this in mind, we need not send a reference to the dispatch function to the useFetching hook as a parameter but rather, simply not send it and rather simply use it from within the useFetching hook with the appropriate imports.
Here's an excerpt of what I mean.
import { useDispatch } from 'react-redux';
const useFetching = (someFetchActionCreator) => {
const dispatch = useDispatch()
useEffect(() => {
dispatch(someFetchActionCreator());
}, [])
}
I can't ascertain this example will fit without errors in your codebase in your case but just trying to explain the idea/concept behind this post.
Hope this helps any future comer.
Alex Hans right decision with dispatch, but to eliminate request loops to api you can specify the dependence on dispatch ( I used Redux Toolkit )
import React, { useEffect } from 'react'
import { useDispatch } from 'react-redux'
import axios from 'axios'
import { getItemsStart, getItemsSuccess, getItemsFailure } from '../features/itemsSlice'
const fetchItems = () => async dispatch => {
try {
dispatch(getItemsStart());
const { data } = await axios.get('url/api')
dispatch(getItemsSuccess(data))
} catch (error) {
dispatch(getItemsFailure(error))
}
}
const PageA = () => {
const dispatch = useDispatch()
const { items } = useSelector(state => state.dataSlice)
useEffect(() => {
dispatch(fetchItems())
}, [dispatch])
return (
<ul>
{items.map(item => <li>{item.name}</li>}
</ul>
)
}
export default PageA
it is important to passed dependency parameter of dispatch in the useEffect(() => {...}, [dispatch])
useEffect(() => {
fetchData();
}, []);
async function fetchData() {
try {
await Auth.currentSession();
userHasAuthenticated(true);
} catch (e) {
if (e !== "No current user") {
alert(e);
}
}
dispatch(authentication({ type: "SET_AUTHING", payload: false }));
}
My folder structure:
|--App
|--Components
|--PageA.js
|--PageB.js
|--PageC.js
|--common-effects
|--useFetching.js
I am refactoring my code to fetch data from API, using react hooks.
I want to dispatch an action from useEffect in useFetching.js that is intercepted by saga middleware. The action should be dispatched only when the components(PageA, PageB, PageC) mount.
I am using redux, react-redux and redux-saga.
PageA.js:
function(props) {
useFetching(actionParams)
//....//
}
Similar code for PageB and PageC components.
I have abstracted the reusable code to fetch data in useFetching Custom hook.
useFetching.js
const useFetching = actionArgs => {
useEffect( () => {
store.dispatch(action(actionArgs)); // does not work
})
}
I don't know how to access redux dispatch in useFetching. I tried it with useReducer effect, but the sagas missed the action.
Version using react-redux hooks:
You can even cut out the connect function completely by using useDispatch from react-redux:
export default function MyComponent() {
useFetching(fetchSomething);
return <div>Doing some fetching!</div>
}
with your custom hook
import { useDispatch } from 'react-redux';
const useFetching = (someFetchActionCreator) => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(someFetchActionCreator());
}, [])
}
Edit: removed dispatch from custom hook as suggested by #yonga-springfield
Note: React guarantees that dispatch function identity is stable and won’t change on re-renders. This is why it’s safe to omit from the useEffect or useCallback dependency list.
You would need to pass either bound action creators or a reference to dispatch to your hook. These would come from a connected component, same as you would normally use React-Redux:
function MyComponent(props) {
useFetching(props.fetchSomething);
return <div>Doing some fetching!</div>
}
const mapDispatch = {
fetchSomething
};
export default connect(null, mapDispatch)(MyComponent);
The hook should then call the bound action creator in the effect, which will dispatch the action accordingly.
Also, note that your current hook will re-run the effect every time the component is re-rendered, rather than just the first time. You'd need to modify the hook like this:
const useFetching = someFetchActionCreator => {
useEffect( () => {
someFetchActionCreator();
}, [])
}
This is just to bring some optimization to #Alex Hans' answer.
As per the documentation here. A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks.
With this in mind, we need not send a reference to the dispatch function to the useFetching hook as a parameter but rather, simply not send it and rather simply use it from within the useFetching hook with the appropriate imports.
Here's an excerpt of what I mean.
import { useDispatch } from 'react-redux';
const useFetching = (someFetchActionCreator) => {
const dispatch = useDispatch()
useEffect(() => {
dispatch(someFetchActionCreator());
}, [])
}
I can't ascertain this example will fit without errors in your codebase in your case but just trying to explain the idea/concept behind this post.
Hope this helps any future comer.
Alex Hans right decision with dispatch, but to eliminate request loops to api you can specify the dependence on dispatch ( I used Redux Toolkit )
import React, { useEffect } from 'react'
import { useDispatch } from 'react-redux'
import axios from 'axios'
import { getItemsStart, getItemsSuccess, getItemsFailure } from '../features/itemsSlice'
const fetchItems = () => async dispatch => {
try {
dispatch(getItemsStart());
const { data } = await axios.get('url/api')
dispatch(getItemsSuccess(data))
} catch (error) {
dispatch(getItemsFailure(error))
}
}
const PageA = () => {
const dispatch = useDispatch()
const { items } = useSelector(state => state.dataSlice)
useEffect(() => {
dispatch(fetchItems())
}, [dispatch])
return (
<ul>
{items.map(item => <li>{item.name}</li>}
</ul>
)
}
export default PageA
it is important to passed dependency parameter of dispatch in the useEffect(() => {...}, [dispatch])
useEffect(() => {
fetchData();
}, []);
async function fetchData() {
try {
await Auth.currentSession();
userHasAuthenticated(true);
} catch (e) {
if (e !== "No current user") {
alert(e);
}
}
dispatch(authentication({ type: "SET_AUTHING", payload: false }));
}