0
votes

Depending on one variable I want to implement conditional rendering. Source code:

  1. My variable

    let hideDeleteButton = false;
    
  2. useEffect - to check value of the variable

    useEffect(() => {
      if (projects?.length === 0 || useCases?.length === 0) {
        hideDeleteButton = false;
      } else {
         hideDeleteButton = true;
      }
    }, []);
    
  3. Conditional rendering

    const DeleteButton = () =>
     hideDeleteButton ? (
       <Tooltip
         content={<TooltipContent title="The component belongs to either project or use case." />}
       >
         <span>
           <Button disabled onClick={handleDelete} color="error" classes={{ root: classes.button }}>
             {t('catalogPage.componentDetails.actionBar.deleteComponent')}
           </Button>
         </span>
       </Tooltip>
     ) : (
       <Button onClick={handleDelete} color="error" classes={{ root: classes.button }}>
         {t('catalogPage.componentDetails.actionBar.deleteComponent')}
       </Button>
     );
    
    return (
     <ActionBar>
       <DeleteButton />
     </ActionBar>
    );
    

And I got such kind of warning:

Assignments to the 'hideDeleteButton' variable from inside React Hook useEffect will be lost after each render. To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property. Otherwise, you can move this variable directly inside useEffect

What sould I do exactly?

1

1 Answers

1
votes

For any rendering related stuff, use a state instead of a ref. Changing a ref won't trigger a render.

let hideDeleteButton = false;

can be

const [hideDeleteButton,setHideDeleteButton] = useState(false);

and then in your useEffect :-

useEffect(() => {
  const hideDeleteButton = projects?.length === 0 || useCases?.length === 0)?false:true 
setHideDeleteButton(hideDeleteButton);
}, []);

Also important stuff - declaring simply let ,var or const variables isn't useful in React flow. In each render they will be reinitialized and lose their old values. Here a ref is of no use since you want a conditional render. It would make sense where you don't want a value to participate in render flow but still want to remember that value between multiple renders for any other use case.