Part 05 - React Notebook
Part 05 - React Notebook
What is Next.js?
Next.js is a React framework that adds features like server-side rendering (SSR), static site
generation (SSG), incremental static regeneration (ISR), built-in routing, and API routes. It
enhances performance and SEO while still using React’s component-based approach.
Conclusion
• React: A versatile, component-based library backed by a huge community and ecosystem.
• Next.js: Extends React with SSR, routing, and server-side features for high-performance,
SEO-focused projects.
• Alternatives (Angular, Vue, Svelte): Offer unique advantages depending on project needs
and developer preferences.
What is package.json?
package.json is a file used in Node.js and JavaScript projects to manage the metadata,
dependencies, scripts, and configuration of the application. It acts as the manifest file for your
project and is essential for any project using npm or Yarn.
Purpose of package.json
1. Project Metadata:
• Provides details about the project, such as its name, version, author, and description.
• Useful for understanding and documenting the purpose of the project.
2. Dependency Management:
• Lists all the libraries (dependencies) the project uses.
• Ensures the project can install the required dependencies with a single command (npm
install).
3. Scripts: Automates common tasks like starting a development server, running tests, or
building the project.
4. Version Control: Helps maintain and share consistent versions of dependencies across
environments.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To-Do App</title>
</head>
<body>
<div id="root"></div>
<script src="index.js" type="module"></script>
<noscript>You need to enable JavaScript to run this app.</noscript>
</body>
</html>
• <div id="root"></div>: A container for the React app.
• <noscript>: Message for users with JavaScript disabled.
index.js (React 17 or earlier)
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
App.js
import React from 'react';
Attributes in JSX:
• Use className instead of class.
• Use camelCase for HTML attributes (e.g., tabIndex instead of tabindex).
Fragments:
• Use <>...</> or <React.Fragment>...</React.Fragment> to return multiple elements
without extra DOM nodes.
Components
• Why Components?
o Break down the UI into small, reusable pieces.
o Each component manages its own logic and state.
Example: Header.js
import React from 'react';
Update Header.js
const Header = ({ title }) => {
return (
<header>
<h1>{title}</h1>
</header>
);
};
Common Hooks:
• useState: Manage local state.
• useEffect: Handle side effects (data fetching, subscriptions).
• useContext: Access global state.
• useReducer: Manage complex state logic.
What is useState?
useState is a Hook that adds local state to functional components. Each call creates a piece of
state that you can read and update.
Syntax
const [state, setState] = useState(initialValue);
return (
<div style={{ textAlign: 'center', marginTop: '50px' }}>
<h1>Counter: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Decrement</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
};
<input
type="text"
placeholder="Enter your name"
onChange={(e) => setName(e.target.value)}
/>
return (
<AppContext.Provider value={{ items, setItems }}>
{children}
</AppContext.Provider>
);
};
Note: Make sure the value prop is provided to AppContext.Provider, as shown above, so child
components can access it.
ReactDOM.render(
<AppProvider>
<App />
</AppProvider>,
document.getElementById('root')
);
By wrapping the entire application in <AppProvider>, every component inside <App /> can access
the global state values provided by AppContext.
3. Accessing Context in Components Example: In App.js, we can use useContext to read and
update the global state:
import React, { useContext, useState } from 'react';
import { AppContext } from './context/AppContext';
import Header from './components/Header';
return (
<div>
<Header title="Global State Management" />
<input
type="text"
onChange={(e) => setItems([...items, e.target.value])}
placeholder="Add an item"
/>
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
</div>
);
};
return (
<ReducerContext.Provider value={{ state, dispatch }}>
{children}
</ReducerContext.Provider>
);
};
• Imports: createContext creates a context to share state, and useReducer manages state
transitions using a reducer function.
• Initial State: initialState is set to { count: 0 }, defining the default state before any actions
are dispatched.
• Reducer Function: The reducer takes state and action and returns a new state based on
the action’s type. In this example:
o 'increment' increases the count by 1.
o 'decrement' decreases the count by 1.
o 'reset' sets the count back to 0.
• Context and Provider: ReducerContext is created to store and distribute state.
ReducerProvider wraps children with a ReducerContext.Provider, passing down state and
dispatch.
ReactDOM.render(
<React.StrictMode>
<ReducerProvider>
<AppProvider>
<App />
</AppProvider>
</ReducerProvider>
</React.StrictMode>,
document.getElementById('root')
);
• By wrapping <App /> with <ReducerProvider>, every component inside <App /> can
access the global state and dispatch function from the reducer.
<input
type="text"
placeholder="Enter your name"
onChange={(e) => setName(e.target.value)}
/>
</div>
);
};
Installation:
npm install react-router-dom
Defining Routes
import { Routes, Route } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import Navbar from './components/Navbar';
function App() {
return (
<div>
<Navbar />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="*" element={<PageNotFound />} />
</Routes>
</div>
);
}
• <Routes>: Introduced in React Router v6, it replaces <Switch>. It renders the first
matching route.
• <Route>: Defines a path and the component to render when that path matches the URL.
• path and element props: path specifies the route segment, and element specifies the
component to render for that path.
• 404 or "Not Found" route : This route will catch all unmatched URLs and render a "Page
Not Found" component, which can include a link back to your Home page or another valid
section of the site.
header {
background-color: #4caf50;
color: white;
padding: 10px;
text-align: center;
}
Import the CSS in App.js:
import './styles/App.css';
useEffect Hook
The useEffect hook is a powerful way to handle side effects in React functional components. Side
effects can include tasks such as data fetching, setting up event listeners, managing timers, or
establishing subscriptions. With useEffect, it’s crucial to understand when the effect runs and how
to clean it up to prevent memory leaks or unwanted behavior.