Introduction to React for Beginners Part 2
Introduction to React for Beginners Part 2
5. Routing in React
Routing is a process in which a user is directed to different pages based on their action or request. React Router is a standard library system built on top of the React and used to create routing in the React application using React Router Package¹[12]12.
Here's an example of basic routing in React:
import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
function AppRouter() {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about/">About</Link>
</li>
<li>
<Link to="/users/">Users</Link>
</li>
</ul>
</nav>
<Route path="/" exact component={Home} />
<Route path="/about/" component={About} />
<Route path="/users/" component={Users} />
</div>
</Router>
);
}
export default AppRouter;
In this example, we have three routes: Home, About, and Users. Each route is linked to a component. When you click on a link, the corresponding component renders¹[12]12.
6. Advanced Topics
6.1 Custom Hooks
Custom Hooks are a mechanism to reuse stateful logic (such as setting up a subscription and remembering the current value), but every time you use a custom Hook, all state and effects inside of it are fully isolated²[1]1.
Here's an example of a custom hook that fetches data from an API:
import { useState, useEffect } from "react";
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
async function fetchData() {
const response = await fetch(url);
const data = await response.json();
setData(data);
setLoading(false);
}
useEffect(() => {
fetchData();
}, []);
return { data, loading };
}
export default useFetch;
6.2 Error Boundaries
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI²[1]1.
Here's an example of an error boundary:
import React from "react";
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
logErrorToMyService(error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary;
6.3 Context API
The Context API is a component structure provided by the React framework, which enables us to share specific forms of data across all levels of the application²[1]1.
Here's an example of using the Context API:
import React, { useContext } from "react";
const ThemeContext = React.createContext("light");
function App() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar() {
return (
<div>
<ThemedButton />
</div>
);
}
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button theme={theme}>I am styled by theme context!</button>;
}
export default App;
6.4 Optimization
React offers several ways to optimize your components, making them faster and more efficient. Techniques include using PureComponent
, memo
, and the useCallback
and useMemo
hooks²[1]1.
Remember, this is just a brief introduction. To fully understand and master React, you'll need to dive deeper into each of these topics and practice building your own React applications. Happy coding! 😊