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.
Related Articles
React Tutorial - Transferring Props
Publish Date:2025/03/16 Views:185 Category:React
-
React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.
React Tutorial: Props Anti-Pattern
Publish Date:2025/03/16 Views:183 Category:React
-
React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.
React Tutorial - Props Validation
Publish Date:2025/03/16 Views:99 Category:React
-
Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.
React tutorial: Types of Props for child components
Publish Date:2025/03/16 Views:170 Category:React
-
Usually, the child components of a React component are a group, that is, the child components are an array. Introduction to Type of the Children Props.
How to solve the error Uncaught TypeError: Cannot read properties of undefined in
Publish Date:2025/03/16 Views:150 Category:React
-
In the process of React development, we often encounter some errors. Here we look at an error reported in App.js. The error is as follows: App.js:69 Uncaught TypeError: Cannot read properties of undefined (reading 'setState') at onInput
Why do you need to bind event handlers in React Class Components?
Publish Date:2025/03/16 Views:58 Category:React
-
When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:
Solution to the error "does not contain a default export" in React
Publish Date:2025/03/16 Views:187 Category:React
-
When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.
Error in React: Attempted import error 'X' is not exported from Solution
Publish Date:2025/03/16 Views:76 Category:React
-
In React, the error “Attempted import error 'X' is not exported from” in React.js occurs when we try to import a named import that does not exist in the specified file. To fix the error, make sure the module has named exports and you have not obfu
Solve the Module not found: Can't resolve 'react-bootstrap' error
Publish Date:2025/03/16 Views:85 Category:React
-
To resolve the error "Module not found: Error: Can't resolve 'react-bootstrap'", make sure to install the react-bootstrap package by opening a terminal in the root directory of the project and running the command `npm install react-bootstrap bootstrap