I'm new to React and try to create my first SPA with React Router.
I try to do it with a functional components.
For now it's very basic but even now I faced a problem which I cannot resolve - component renders twice every time I use proper routing.
Problem appeared when I started to use useEffect
hook to call simple console.log()
on component initialisation. I noticed every time I choose Autosearch
from a Navbar
React Router render proper component but I can see two logs Called!
in a browser console. I've tried recompose structure of my HTML but it didn't work.
index.js
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<BrowserRouter>
<App/>
</BrowserRouter>
</React.StrictMode>
);
App.js
function App() {
return (
<div className="container-background h-auto">
<div className="container-lg p-2">
<Header/>
<Navbar/>
<section className="content p-4">{<ContentDisplay/>}</section>
<Footer/>
</div>
</div>
);
}
Navbar.js
const Navbar = () => {
return (
<React.Fragment>
<nav className="navbar nav-custom">
<span className="navbar-collapse">
<div className="nav">
<NavLink className="nav-item nav-link text-white" to={"/reversed"}>Reversed</NavLink>
<NavLink className="nav-item nav-link text-white" to={"/autosearch"}>AutoSearch</NavLink>
<NavLink className="nav-item nav-link text-white" to={"/about"}>About</NavLink>
</div>
</span>
</nav>
</React.Fragment>
);
}
ContentDisplay.js
const ContentDisplay = () => {
return (
<>
<Routes>
<Route path="/" exact element={<Home/>} />
<Route path="/reversed" exact element={<Reversed />} />
<Route path="/autosearch" exact element={<Autosearch />} />
<Route path="/about" exact element={<About />} />
<Route path="*" element={<ErrorPage />} />
</Routes>
</>
)
}
Autosearch.js
const Autosearch = () => {
useEffect(() => {
console.log("Called!")
}, []);
return(
<>
Autosearch
</>
)
}