Germán
Germán

Reputation: 1311

React Component displays Console.log twice, with previous and new value

I have the following component where console.log displays twice, once with the previous value and another with the new change. I don't know why is the reason for this behaviour, but I mostly ask because I'm worried that the component could be rendered twice due to some mistake and eventually the app could be overloaded due to bad coding.

    function Topbar() {

      const {pathname} = useLocation();
      const [title,SetTitle] = useState(SidebarData.find(ruta => ruta.path === pathname).title)
  
      useEffect(()=>{
          SetTitle(SidebarData.find(ruta => ruta.path === pathname).title);
      },[pathname]);

      console.log(title); //displays twice
  
      return (
        <>
          <IconContext.Provider value={{color: '#fff'}}>
          <div className='topbar'>{title}</div>
          </IconContext.Provider>
        </>
      );
    }

    export default Topbar;

Upvotes: 0

Views: 1327

Answers (1)

Zorkiy
Zorkiy

Reputation: 9

You can just move 'SidebarData.find(ruta => ruta.path === pathname).title' fragment into const and just call it in useEffect. There is no need to call this structure in useState.

function Topbar() {

      const {pathname} = useLocation();
      const [title,SetTitle] = useState('');

      const titleCalculation = SidebarData.find(ruta => ruta.path === pathname).title;

      useEffect(() => {
          SetTitle(titleCalculation);
      },[pathname]);

      console.log(title); //displays twice
  
      return (
        <>
          <IconContext.Provider value={{color: '#fff'}}>
            <div className='topbar'>{title}</div>
          </IconContext.Provider>
        </>
      );
    }

 export default Topbar;

Upvotes: 0

Related Questions