L
L
lexstile2020-05-14 10:48:00
React
lexstile, 2020-05-14 10:48:00

I can not understand why on click the component is rendered twice?

There is a menu, it has items, a handler is hung on them.
By clicking on an item, it is rendered, if you click on it (the same item) again, it is rendered again (it is not rendered only after 2 clicks on the same element), this should not be. How can I fix it?

App.jsx

spoiler
const AppComponent = () => {
  const [activePage, setActivePage] = useState('home');

  const handleClickMenuItem = useCallback((page) => () => setActivePage(page), []);

  console.log('activePage', activePage);
  return (
    <>
      <Header />
      <Footer activePage={activePage} onClick={handleClickMenuItem} />
    </>
  );
};

export const App = memo(AppComponent);

footer.jsx
spoiler
const withIcon = (Icon, color) => <Icon fill={color} width={28} height={28} />;

const FooterComponent = ({ activePage, onClick }) => (
  <div className={cx('footer')}>
    {menuItems.map(({ alias, icon }) => (
      <div key={alias} className={cx('nav-item')} onClick={onClick(alias)}>
        {withIcon(icon, alias === activePage ? '#3f8ae0' : '#99a2ad')}
      </div>
    ))}
  </div>
);

export const Footer = memo(FooterComponent);


5ebcf8b44d79c155901101.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Aves, 2020-05-18
@lexstile

https://reactjs.org/docs/strict-mode.html#detectin...
Correct me, in dev mode the entire Functional component is called twice.

M
Mikhail Osher, 2020-05-14
@miraage

// take this
onClick={onClick(alias)}>
// change to this
onClick={() => onClick(alias)}>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question