Context provides a way to pass data through the component tree without having to pass props down manually at every level.
const ThemeContext = createContext();
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
};
const { theme, setTheme } = useContext(ThemeContext);
return (
<div>
<p>Current Theme: {theme}</p>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
</div>
);
Demonstration of creating a sidebar switcher using useContext and providers to manage the theme state.
Demonstration of creating an AuthContext to manage authentication state
Recap of the benefits of using useContext and providers in React to efficiently manage state across components.
import { BrowserRouter } from 'react-router-dom';
function App(){
return (
<BrowserRouter>
<App/>
</BrowserRouter>
)
}
A hook that returns an element that renders the first matching child route.
const Routes = () => {
const routes = useRoutes([
{ path: '/', element: <Home /> },
{ path: '/about', element: <About /> },
{ path: '/contact', element: <Contact /> },
{ path: '/user/:username', element: <UserProfile /> },
]);
return routes;
};
A component used to create navigational links. Uses the to prop to specify the target URL.
<Link to="/register" />
<Link to="/login" replace/>
A hook that provides a function to programmatically navigate between routes.
const navigate= useNavigate();
const onSubmit=()=>{
navigate("/profile")
}
A hook that returns the current location object, which represents where the app is now, where it was before, and how it got there.
function LocationDisplay() {
const location = useLocation();
return (
<div>
<h2>Current Location</h2>
<pre>{JSON.stringify(location, null, 2)}</pre>
</div>
);
}
A hook that returns an object of key-value pairs of the URL parameters.
function UserProfile() {
const { username } = useParams();
return (
<div>
<h2>User Profile</h2>
<p>Username: {username}</p>
</div>
);
}
Routing:
/users/:username
Example:
/users/youcefM
This hook allows you to read and manipulate the query string in the URL. It's useful for scenarios where you need to read or update URL query parameters.
function UserProfile() {
const { username } = useParams();
const [searchParams, setSearchParams] = useSearchParams();
const age = searchParams.get('age');
const handleAgeChange = (e) => {
setSearchParams({ age: e.target.value });
};
// rest
}
Routing:
/users/:username?age=
Example:
/users/youcefM?age=26
This hook allows you to read and manipulate the query string in the URL. It's useful for scenarios where you need to read or update URL query parameters.
return (
<div>
<h2>User Profile: {username}</h2>
<p>Age: {age}</p>
<input
type="number"
value={age || ''}
onChange={handleAgeChange}
placeholder="Set age"
/>
</div>
);
Routing:
/users/:username?age=
Example:
/users/youcefM?age=26