When we use create-react-app
to generate our application source code, we will be provided with a base code that enables React.StrictMode
by default. This wrapper component doesn't render an HTML element but it performs useful functionality to verify that our application is safe for production. It checks for legacy or deprecated React functions or APIs, unexpected side-effects, and unsafe lifecycle. We can read the details about those functionalities on its documentation page.
To help us spot side-effects, React will double-invoking several functions in our application such as render
, constructor
, functions passed in useMemo
or useReducer
, and so on. By double-invoking such functions, we can detect if unexpected results will show up. But, this process will be initiated only in development mode. When we ship our application in a production environment with Strict Mode enabled, double-invoking will never happen. This is why when we render a component that contains useEffect
to fetch some data, the process is performed twice. Then, if we don't handle the data correctly, we will face unexpected side-effects like double entries or inconsistent states.
For instance, we have a fetching function that retrieves a list of articles and then stored it in a state. It may cause duplicate entries if the function is run twice then we just merge the result with the existing one.
const articles = [...existingArticles, ...newArticles];
Now, we need to be more careful in merging any records.
newArticles.forEach((na) => {
if (!existingArticles.find((ea) => ea.id === na.id)) {
articles.push(na);
}
});
Comments
Post a Comment