React usestate updates twice when clicking a button

  javascript, reactjs, use-state

I have a dropdown that appears when a button is clicked inside of react table.

function Table({ columns, data, getTrProps, isShowing }) {
  const [isVisible, setIsVisible] = useState(false);
  const currentColOrder = React.useRef();
  const { store } = useContext(AppContext);

  const handleChange = () => {
    setIsVisible(() => !isVisible);
  };

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
    allColumns,
    visibleColumns,
    setColumnOrder,
    getToggleHideAllColumnsProps,
  } = useTable(
    {
      columns,
      data,
    },
    useSortBy,
    useRowSelect,
    useColumnOrder,

    hooks => {
      hooks.visibleColumns.push(columns => [
        {
          id: 'selection',
          className: 'selection',
          disableSortBy: true,
          accessor: '',

          Header: ({ getToggleAllRowsSelectedProps }) => (
            <div>
              <IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} />
            </div>
          ),

          Cell: ({ row }) => (
            <div>
              <IndeterminateCheckbox {...row.getToggleRowSelectedProps()} />
            </div>
          ),
        },
        ...columns,
        {
          className: 'Columns_Menu',
          disableSortBy: true,
          id: 'Eye',
          Header: () => (
            <StyledEyeButton type="button" onClick={handleChange} id="eye">
              <Eye />
            </StyledEyeButton>
          ),

          Cell: () => <div />,
        },
      ]);
    },
  );

The value isVisible is initially false. When I click the StyledEyeButton the dropdown opens like it should and the isVisible value is changed to true. However when I click the button again to close the dropdown the value for isVisible switches to false and then switches a second time back to true so the dropdown never closes. I have an on outside click function that is passed down to the dropdown in the table and when you click outside the dropdown it closes fine, but it’s just when you try to click the eye button to close the dropdown after opening that the problem arises. I thought that using an anonymous function in the handleChange was supposed to fix the problem, but it doesn’t. Any ideas what’s causing this? The only thing I can think of is because the button itself is being rendered from a function and this is causing a state issue, but I wasn’t sure because the button shouldn’t be re-rendered after initial load.

Source: Ask Javascript Questions

LEAVE A COMMENT