React helps us to share data between components and navigate b/w different pages without reloading the entire website.
1.UseContext:
It is a React Hook Component that allows to access shared data without passing props through every intermediate component and avoid props drilling.
Example:
`import {createContext,useContext} from "react";
const UserContext = createContext();
function App(){
return(
);
}
function Profile(){
const user = useContext(UserContext);
return
Welcome{user}
;}
export default App;`
Output:
Welcome Sam
`
2.React Router:
React Router is a library used to handle navigation between diffrent routes in a react application.
Example:
An application have
- Home page
- About page
- Contact page
- Login page
React router helps us display the correct component based on current url.
3.What is BrowserRouter?
It is a router component that uses browser's history API to manage navigation.
It allows us to use normal URLs such as:
- /home
- /aboutus
- /contact _ Example:_ `import{BrowserRouter} from "react-router-dom";
function App(){
return(
{/Routes will be placed here/}
);
}
export default App;`
4.What is Router and Routes?
A route connects a URL path wih a particular React component.
Example:
`import{BrowserRouter,Routes,route} from "react-router-dom";
function Home(){
return
Home Page
;}
function About(){
return
About Page
}
function App(){
return(
}/>
}/>
);
}
export default App;``
Here:
- BrowserRouter manages browser navigation.
- Routes contain route definitions.
- Routes connect URL path to a component.
- element specifies which component should be displayed.
5.What is Link in React Router?
Link is used to navigate between diffrent routes without reloading the entire page.
Example:
`import {Link} from "react-router-dom";
function Navbar(){
return(
);
}
`
The to attribue specifies the destintion route.
6.What is useNavigate()?
useNavigate() is a React Router Hook component to navigate from one route to another.
_
example:_
submitting a login form,we may want to navigate to another page.
import{useNavigate} from "react-router=dom";
function Login(){
const navigate = useNavigate();
function handleLogin(){
navigate("/home");
}
return(
Login
);
}``
When button is clicked ,the user is navigated to /home.
Diffrence Between Link and useNavigate()
Link ** ** UseNavigate()
Used for navigation through a link. Used for navigation through
Javascript.
Commonly used in navigation bars. Commonly used after an action.
Uses the to prop. Uses the navigate() function.
What I Learned today
Today i learned how useContext helps avoid Props Drilling and how React Router handles navigation between diffrent pages.
I also explored BrowserRouter,Routes,Route,Link and useNavigate().