react package
- import {useEffect} from "react";
- context hooks in react
- @types/react
- import React from 'react'
- createbrowserrouter in react
- useMemo,useLocation from react
import {useEffect} from "react";
import {useEffect} from "react"; is a JavaScript import declaration used in React applications. useEffect Hook from the React library. The useEffect Hook is a fundamental part of functional components in React, enabling developers to perform "side effects." - Data fetching: Making API calls to retrieve data from a server.
- DOM manipulation: Directly interacting with the browser's Document Object Model (e.g., setting the document title).
- Subscriptions: Setting up event listeners or connecting to external services like WebSockets.
- Timers: Using
setTimeoutorsetInterval.
useEffect Works: useEffect takes two arguments: -
A setup function:This function contains the code for your side effect. It runs after every render of the component (including the initial render) unless its dependencies prevent it from doing so.
-
A dependency array (optional):This array specifies the values that the effect depends on. If any of these values change between renders, the effect will re-run. An empty dependency array
[]ensures the effect runs only once after the initial render (similar tocomponentDidMountin class components).
import { useEffect, useState } from "react";
function MyComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
// This side effect updates the document title
document.title = `Count: ${count}`;
}, [count]); // The effect re-runs whenever 'count' changes
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default MyComponent;
context hooks in react
useContext, allow functional components to subscribe to and consume data from React's Context API, simplifying global state management by avoiding "prop drilling" (passing props down many levels). You create a Context with React.createContext(), wrap parts of your app with a Provider to pass data down, and then use useContext(MyContext) in any nested component to read that data, making it ideal for themes, authentication, or user settings.
React.createContext(): Creates a Context object, often with a default value, that components can subscribe to.<Context.Provider>: A component that wraps a part of your component tree and uses thevalueprop to provide data to all descendants.useContext(Context): A hook used in functional components to read the current context value from the nearestProviderabove it in the tree.
- Create Context:
javascript
-
import { createContext } from 'react'; const ThemeContext = createContext('light'); // Default value - Provide Context: Wrap components with the
Providerhigh up in the tree.javascript -
function App() { return ( <ThemeContext.Provider value="dark"> <Toolbar /> </ThemeContext.Provider> ); } - Consume Context: Use
useContextin any child component to get the value.javascript
import { useContext } from 'react';
function Toolbar() {
const theme = useContext(ThemeContext); // Gets "dark"
return <div>The current theme is: {theme}</div>;
}
- Avoids Prop Drilling: Eliminates the need to pass props through intermediate components that don't need the data.
- Simpler Syntax: More concise and declarative than older methods (like render props or Consumer components) for functional components.
- Global State: Great for sharing data like themes, user info, or language settings across an application.
useContext call and error handling (e.g., checking for null if used outside a provider). // useTheme.js
import { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
export function useTheme() {
const context = useContext(ThemeContext);
if (context === undefined) {
throw new Error('useTheme must be used within a ThemeProvider');
}
return context;
}
@types/react
@types/react is the npm package containing TypeScript definitions for the React library, essential for building React apps with TypeScript to get type-checking for components, props, hooks (like useState, useEffect), and rendering types (like ReactNode). It provides the necessary structure for TypeScript to understand React's API, enabling features like autocompletion and catching errors before runtime, with types such as React.FC for functional components or React.ReactNode for renderable content.
- Type Safety: Gives TypeScript knowledge of React's functions, components, and props.
- Hooks Support: Includes types for all built-in React hooks, allowing their correct usage.
- Component Definition: Helps define component props, including
children(often asReact.ReactNode). - Rendering Types: Defines types like
React.Element,React.ReactNode(anything renderable),JSX.Element, etc..
- Install it as a development dependency:
npm install --save-dev @types/reactoryarn add @types/react. - It's typically installed alongside
@types/react-domfor full type support in your React+TypeScript projects.
React.FC<Props>: For functional components.React.ReactNode: For props that accept anything renderable (children, content).React.HTMLAttributes<T>: For standard HTML attributes on components.
- Ensure your
@types/reactversion matches yourreactversion for consistency, as mismatches can cause issues (e.g., React 18 changes required corresponding type updates)
import React from 'react'
import React from 'react'is a JavaScript statement to bring the React library into your file, historically required to use JSX (like <div>) because it converts to React.createElement(), though newer React versions with the "new JSX transform" (React 17+) often make it optional for basic JSX, but it's still needed for Hooks (like useState) and other exports, with import * as React from 'react' also common for importing everything into a React object.
- Imports React: It makes the
Reactobject, containing methods likecreateElement, available in your component. - Enables JSX: Before React 17, this line was essential because JSX syntax (e.g.,
<p>Hello</p>) gets transformed intoReact.createElement(<p>, null, 'Hello').
import React from 'react': Imports the default export (the whole library) and names itReact. Still needed for Hooks.import * as React from 'react': Imports all named exports into a singleReactobject. Useful in TypeScript or with specific bundler setups.- No import (for simple components): With React 17+, the new JSX transform handles basic JSX without needing the import, but you still need it for hooks.
- Specific imports: For efficiency, import only what you need, e.g.,
import { useState } from 'react'.
import React from 'react'; // Required for React.useState
function Counter() {
const [count, setCount] = React.useState(0); // Uses React.useState
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
// import React from 'react'; // Not strictly needed for just JSX
function Greeting({ name }) {
// No React. prefix needed for useState with this setup
return <h1>Hello, {name}!</h1>;
}
createbrowserrouter in react
createBrowserRouterin React Router (v6.4+) creates a router using a data-driven approach (array of route objects) instead of JSX, enabling powerful features like data loading (loaders) and mutations (actions), and is the recommended modern way for web apps by managing history via the HTML5 History API for clean URLs. You define routes as objects with path and element (or children) and pass them to createBrowserRouter, then wrap your app with the RouterProvider component.
createBrowserRouter- Install React Router:
bash
-
npm install react-router-dom # or yarn add react-router-dom - Define Your Routes (e.g., in
router.jsorindex.js):javascript -
import { createBrowserRouter } from 'react-router-dom'; import Root from './routes/Root'; // Your main layout component import Home from './routes/Home'; import About from './routes/About'; import ErrorPage from './routes/ErrorPage'; const router = createBrowserRouter([ { path: "/", element: <Root />, errorElement: <ErrorPage />, children: [ // Nested routes { index: true, element: <Home /> }, // Renders <Home> at '/' { path: "about", element: <About /> }, { path: "users/:userId", element: <UserProfile /> }, // Dynamic route ], }, ]); export default router;path: The URL segment.index: trueis for the default child route.element: The component to render for that path.children: For nested routes, uses<Outlet />in the parent.
- Provide the Router (in
index.jsorApp.js):javascript
import React from 'react';
import ReactDOM from 'react-dom/client';
import { RouterProvider } from 'react-router-dom';
import router from './router'; // Your router config
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>,
);
<BrowserRouter>/JSX Routes)- Data Layer: Supports
loaderfunctions for fetching data before rendering, ensuring components get data immediately. - Data Mutations: Supports
actionfunctions for POST/PUT/DELETE requests, improving data flow. - Flexibility: Configure routes as JS objects (data) instead of JSX, separating concerns.
- Future-Proof: Recommended by React Router as the modern direction
useMemo,useLocation from react
useMemo and useLocation are two distinct hooks in the React ecosystem, serving different purposes. useMemo (from react) useMemo is a React Hook that allows for memoization of a value. This means it caches the result of an expensive calculation and only re-runs the calculation if its dependencies change. This can significantly improve performance by preventing unnecessary re-calculations on every render. import React, { useMemo } from 'react';
function MyComponent({ data }) {
// Expensive calculation that only re-runs if 'data' changes
const processedData = useMemo(() => {
// Perform complex data processing here
return data.map(item => item.value * 2);
}, [data]); // Dependencies array
return (
<div>
{/* Render processedData */}
{processedData.map((item, index) => (
<p key={index}>{item}</p>
))}
</div>
);
}
useLocation (from react-router-dom) useLocation is a hook provided by the react-router-dom library, not directly from react. It allows you to access the current URL's location object, which contains information about the current route. This information includes pathname, search (query parameters), hash, and state (data passed during navigation). import React from 'react';
import { useLocation } from 'react-router-dom';
function CurrentRouteInfo() {
const location = useLocation();
return (
<div>
<p>Pathname: {location.pathname}</p>
<p>Search Query: {location.search}</p>
<p>Hash: {location.hash}</p>
{/* Access state data if available */}
{location.state && <p>State Data: {JSON.stringify(location.state)}</p>}
</div>
);
}
-
Origin:
useMemois a core React hook, whileuseLocationis part ofreact-router-dom. -
Purpose:
useMemooptimizes performance by memoizing values, whileuseLocationprovides access to route information. -
Dependencies:
useMemotakes a dependencies array to determine when to re-calculate, whileuseLocationautomatically updates when the URL changes