Home > Mobile >  Is an empty dependency array for React.useEffect not permissible?
Is an empty dependency array for React.useEffect not permissible?

Time:08-10

I have a child React component that is passed an itemList prop from its parent component. This itemList is an object array containing data from an endpoint.

The first thing I want to do within the child component is translate itemList to be more complex, meaning for each object in the array to have more/different properties, etc. I accomplish this via an itemList.map function call.

Because this is a one time operation, my thought was to just have an empty dependency array, like this:

type ObjectMap = {
  key: string,
  text: string,
  parentId?: string|null
};

const [objectItemList, setObjectItemList] = React.useState<Array<ObjectMap>>([]);

React.useEffect(() => {
  if (isEmpty(objectItemList)) {
    const localObjectItemList: Array<ObjectMap> = itemList.map((item, idx) => {
      type ObjectKey = keyof typeof item; // Union of the object array element's keys
      const keyValue = String(item[objectMap.key as ObjectKey]);
      const textValue = String(item[objectMap.text as ObjectKey]);
      let parentIdValue: string|null = String(item[objectMap.parentId as ObjectKey]);
      parentIdValue = parentIdValue === 'null' ? null : parentIdValue;
      return {key: keyValue, text: textValue, parentId: parentIdValue};
    });

    setObjectItemList(localObjectItemList);
  }
}
// eslint-disable-next-line react-hooks/exhaustive-deps    
}, []); // Including objectItemList cause "Too many renders" error

You can see that I'm suppressing the error but what's confusing is that I would have thought that just the empty dependency array alone would inform eslint to not complain about "missing dependencies".

By the way, as my comment in the code illustrates, if I do include objectItemList as a dependency then I get the other error mentioned.

CodePudding user response:

ESLint is not smart enough to understand the context everytime, it's a set of objective measurements. If you want to run something once, guaranteed, use an empty dependency array and suppress the warning. It's a warning, not an error.

CodePudding user response:

You don't need useState and useEffect at this case. Because the component will rerender if props are changed

const objectItemList = itemList.map(...)
  • Related