react.useeffect hook common problems and solutions
most developers are very familiar with how react hooks work and common use cases, but there is one issue with useeffect that many people may not be clear about.
use cases
let's start with a simple scenario. we are building a react application and want to display the username of the current user in a component. but first, we need to get the username from the api.
because we know we’ll need to use the user data elsewhere in the application as well, we also want to abstract the data fetching logic in a custom react hook.
we want our react component to look like this:
const component = () => {
// useuser custom hook
return <div>{user.name}div>;
};
looks easy enough!
useuser react hook
the second step is to create our useuser custom hook.
const useuser = (user) => {
const [userdata, setuserdata] = usestate();
useeffect(() => {
if (user) {
fetch("users.json").then((response) =>
response.json().then((users) => {
return setuserdata(users.find((item) => item.id === user.id));
})
);
}
}, []);
return userdata;
};
let's break this down. we are checking if the hook is receiving a user object. after that, we users.json
get the list of users from a file called and filter it to find the user with the id we need.
then, once we have the necessary data, we save it as the userdata state of the hook. finally, we return userdata.
注意
: this is an example for illustration purposes only! real-world data fetching is much more complex. if you’re interested in the topic, check out my article on how to create an awesome data fetching setup with reactquery, typescript , and graphql .
let's insert the hook into our react component and see what happens.
const component = () => {
const user = useuser({ id: 1 });
return <div>{user?.name}div>;
};
ok, so everything is working as expected. but wait... what is this?
eslint exhaustive-deps rule
we have an eslint warning in our hook:
react hook useeffect has a missing dependency: 'user'. either include it or remove the dependency array.
(react-hooks/exhaustive-deps)
hmm, our useeffect
seems to be missing a dependency. oh well! let's add it. what's the worst that could happen? 😂
const useuser = (user) => {
const [userdata, setuserdata] = usestate();
useeffect(() => {
if (user) {
fetch("users.json").then((response) =>
response.json().then((users) => {
return setuserdata(users.find((item) => item.id === user.id));
})
);
}
}, [user]);
return userdata;
};
it looks like our component won't stop re-rendering now. what's going on here?!
let us explain.
infinite re-rendering problem
the reason our component is re-rendering is because the useeffect dependency is constantly changing. but why? we always pass the same object to the hook!
while we do pass an object with the same keys and values, it is not the exact same object. we are actually creating a new object each time the component is re-rendered, and then we pass the new object as a parameter to the useuser hook.
internally, useeffect compares the two objects, and since they have different references, it fetches the user again and sets the new user object to the state. the state update then triggers a re-render in the component, and it repeats…
so, what can we do?
how to fix it
now that we understand the problem, we can start looking for a solution.
the first and most obvious option is to remove the dependency from the useeffect dependencies array, ignore the eslint rules, and move on with our lives.
but this is the wrong approach. it can (and probably will) lead to bugs and unexpected behavior in our applications. if you want to learn more about how useeffect works, i highly recommend dan abramov’s complete guide.
what's next?
in our case, the simplest solution is to remove the { id: 1 } object from the component. this will provide a stable reference to the object and solve our problem.
const userobject = { id: 1 };
const component = () => {
const user = useuser(userobject);
return <div>{user?.name}div>;
};
export default component;
but this is not always possible. imagine that the user id depends on component props or state in some way.
for example, it may be that we access it using url parameters. if this is the case, we can use a convenient usememo
hook to memoize the object and ensure a stable reference again.
const component = () => {
const { userid } = useparams();
const userobject = usememo(() => {
return { id: userid };
}, [userid]); // don't forget the dependencies here either!
const user = useuser(userobject);
return <div>{user?.name}div>;
};
export default component;
finally, instead of passing an object variable to our useuser hook, we can just pass the user id itself, which is a primitive value. this will prevent reference equality issues in the useeffect hook.
const useuser = (userid) => {
const [userdata, setuserdata] = usestate();
useeffect(() => {
fetch("users.json").then((response) =>
response.json().then((users) => {
return setuserdata(users.find((item) => item.id === userid));
})
);
}, [userid]);
return userdata;
};
const component = () => {
const user = useuser(1);
return <div>{user?.name}div>;
};
problem solved!
we didn’t even have to break any eslint rules in the process…
注意
if the argument we pass to our custom hook is a function, rather than an object, we’ll use a very similar technique to avoid infinite re-rendering. the one notable difference is that we have tousecallback
replace with in the example aboveusememo
.
for reprinting, please send an email to 1244347461@qq.com for approval. after obtaining the author's consent, kindly include the source as a link.
article url:
related articles
how to use react lazy code splitting
publish date:2025/03/11 views:104 category:react
-
react lazy 函数允许我们动态导入组件。我们可能希望这样做以减少用户必须下载才能在屏幕上看到内容的初始捆绑包大小。
how to loop over objects in react
publish date:2025/03/11 views:50 category:react
-
在 react 中循环一个对象: 使用 object.keys() 方法获取对象键的数组。 使用 map() 方法遍历键数组。
scroll to bottom of div in react
publish date:2025/03/11 views:169 category:react
-
在 react 中滚动到 div 的底部: 在 div 的底部添加一个元素。 在底部的元素上设置一个 ref。 当事件发生时,调用 ref 对象的 scrollintoview() 方法。
how to draw a horizontal line in react
publish date:2025/03/11 views:73 category:react
-
在 react 中画一条水平线: 使用 hr / 标签并在其上设置 style 属性。 设置线条的高度,并可选择设置背景颜色和颜色。
how to use buttons as links in react
publish date:2025/03/10 views:140 category:react
-
要将按钮用作 react 中的链接,请将按钮包装在 标记中,如果使用 react 路由器,则将其包装在 link 组件中。 该按钮将被呈现而不是链接,单击它将导致浏览器导航到指定的页面。
using onclick on div elements in react
publish date:2025/03/10 views:121 category:react
-
要在 react 中的 div 元素上设置 `onclick` 监听器: 在 div 上设置 `onclick` 属性。 每次单击 div 时,都会调用我们传递给 prop 的函数。 我们可以通过 event.currenttarget 访问 div。
react: how to upload multiple files using axios
publish date:2025/03/10 views:146 category:react
-
这篇简洁明了的文章向您展示了如何在 axios 的帮助下在 react 中上传多个文件。这项工作并不太庞大,可以通过以下几个简单的步骤完成(您将在第 3 步中看到 javascript 和 typescript 代码片
how to toggle a boolean state in react
publish date:2025/03/10 views:93 category:react
-
在 react 中切换布尔状态:使用 usestate 钩子来跟踪布尔值的状态。 将函数传递给钩子返回的 setstate 函数。根据当前值切换布尔值,例如 setisloading(current => !current)。
creating a back button with react router
publish date:2025/03/10 views:155 category:react
-
使用 react router 创建后退按钮: 将按钮上的 onclick 属性设置为函数。使用 usenavigate() 钩子,例如 const navigate = usenavigate();。调用 navigate() 函数,传递它 -1 - navigate(-1)。