Home > OS >  React state not updating - only updated after first clicked
React state not updating - only updated after first clicked

Time:10-18

import React, { useEffect, useState } from "react";
import { NavLink, useLocation } from "react-router-dom";

function Navigation() {
  const [pageTitle, setPageTitle] = useState("about");

  useEffect(() => {
    console.log(pageTitle);
  }, [pageTitle]);

  return (
    <div>
      <section className="flex justify-center mt-36">
        <ul className="flex gap-4">
          <NavLink to={"/"}>
            <span className="group transition duration-300">
              about
              <span className="block max-w-0 group-hover:max-w-full transition-all duration-500 h-0.5 bg-sky-600"></span>
            </span>
          </NavLink>
          <NavLink
            to={"/portfolio"}
            onClick={() => {
              setPageTitle("portfolio");
            }}
          >
            <span className="group transition duration-300">
              portfolio
              <span className="block max-w-0 group-hover:max-w-full transition-all duration-500 h-0.5 bg-sky-600"></span>
            </span>
          </NavLink>
        </ul>
      </section>
      <section>
          <span className="flex-shrink mx-4 text-gray-400">{pageTitle}</span>
      </section>
    </div>
  );
}

When I click portfolio, state is not changing. Actually state changes after the first click. I heard that states are asynchronous and have to use useEffect. anyway, I didn't get the point. Where I'm doing something wrong? Thanks.

CodePudding user response:

Put onClick on the <span> tag

          <NavLink
            to={"/portfolio"}
          >
            <span onClick={() => setPageTitle("portfolio")} className="group transition duration-300">
              portfolio
              <span className="block max-w-0 group-hover:max-w-full transition-all duration-500 h-0.5 bg-sky-600"></span>
            </span>
          </NavLink>

CodePudding user response:

this will update after first click because you are updating state inside onClick event, btw when do you want your state to be updated? and your useEffect is of no use here it is just consoling your pageTitle value.

  • Related