I am having a reusable component which takes an editable
prop which can be toggled from outside. The problem is that whenever that toggle is activated the whole component rerenders including API calls which should be only called once. How can i prever rerender if the specific prop editable
changes? Or what is the way to solve this issue?
What i would like to obtain is to get the API call only once in the component no matter how many times the editable
prop changes. How can i achieve this?
Code bellow:
export const EditableTableList: React.FC<EditableTableListProps> = React.memo(({ columns, editEnabled, keyName, getData, sendChangeToParent }) => {
...
// THIS RERENDERS EVERYTIME EDITABLE CHANGES
useEffect(() => {
const getTableData = async () => {
setLoadedData(false);
setOriginalData(await getData());
setLoadedData(true);
}
getTableData();
}, [getData]);
...
}
CodePudding user response:
getData() will re-render every time the parent component will, you could send it as a useCallback function expression so it would retain the same identity even if parent re renders.
CodePudding user response:
The effect is executed again only because your getData
function is changing - maybe not its content but definitely the instance/reference.
You'll have to memoize it in your parent component, for example using useCallback
. If you provide the parent component I could give you an example.