Summary: Learning about React and its components, Next.js a React framework.
React
React is a JavaScript library for building user interfaces. It’s maintained by Facebook and a community of individual developers and companies. React allows developers to create large web applications that can change data, without reloading the page. Its primary purpose is to be fast, scalable, and simple, particularly for developing single-page applications (SPAs) where different components of a web app work together seamlessly.
Components
- React is component-based. This means the UI is broken down into small, reusable, isolated pieces called components. Components make the code more modular, readable, and maintainable.
- Functional Components: These are plain JavaScript functions that return JSX (React’s syntax for templating).
- Class Components: These are ES6 classes that extend React.Component. They have a render method that returns JSX.
- Components can be nested, managed, and handled independently, making complex applications more scalable.
JSX (JavaScript XML)
- React components return JSX, which is an HTML-like syntax but written in JavaScript. Under the hood, JSX gets transformed into regular JavaScript objects using Babel.
- JSX allows embedding JavaScript expressions directly inside curly braces
{}
in the markup.
const element = <h1>Hello, World!</h1>;
Props
- Props are short for properties and are used to pass data from one component to another, typically from a parent component to a child component.
- They are read-only (immutable) and help in customizing or configuring child components.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
State
- While
props
are used to pass data between components, state is used to handle internal data within a component. - State is mutable, meaning it can change over time, and whenever the state changes, the component re-renders.
- State is usually initialized in a class component with
this.state
or with theuseState
hook in functional components.
const [count, setCount] = useState(0);
Lifecycle Methods
- Class components have lifecycle methods that allow developers to hook into different stages of a component’s existence:
- Mounting: when the component is created and added to the DOM.
- Updating: when the component’s props or state changes.
- Unmounting: when the component is removed from the DOM.
- Example lifecycle methods:
componentDidMount()
: called after the component is inserted into the DOM.componentDidUpdate()
: called after the component updates its state or props.componentWillUnmount()
: called before the component is removed from the DOM.
Hooks
- React hooks were introduced in React 16.8 and allow we to use state and other React features in functional components.
- Common hooks:
useState
: Adds state to functional components.useEffect
: Allows performing side effects (e.g., data fetching, DOM manipulation) in function components.useContext
: Passes data down the component tree without having to explicitly pass props.useRef
: Accesses DOM elements directly.
One-way Data Flow
- React applications have a unidirectional data flow. Data flows from parent components to child components via props.
- This helps in understanding the flow of data, debugging, and ensuring that changes in one part of the app don’t affect other parts unexpectedly.
Virtual DOM
- One of React’s core features is the virtual DOM. Instead of interacting directly with the real DOM, React creates a lightweight copy of the DOM called the virtual DOM.
- When the state of an object changes, React updates the virtual DOM, then compares it with the real DOM, and finally, React makes only the necessary changes in the actual DOM.
- This makes the app fast and efficient because direct manipulations of the real DOM are often slow.
Event Handling
- In React, handling events is quite similar to how it’s done in regular HTML/JavaScript but with some key differences.
- Event handlers in React are written in camelCase instead of lowercase (e.g.,
onClick
instead ofonclick
). - Instead of strings, React event handlers are JavaScript functions.
<button onClick={handleClick}>Click me</button>
Context API
- React’s Context API allows us to share state across many components without having to pass props manually at every level.
- It is often used to avoid prop drilling, where we pass props down several layers of the component tree, even to components that don’t need them directly.
- The Context API works by creating a context object that holds some value, then providers and consumers access or update the values.
const ThemeContext = React.createContext();
Next.js
Next.js is a React framework that provides several features for building fast, modern web applications. It is designed to handle server-side rendering (SSR), static site generation (SSG), client-side rendering, API routes, and other advanced features out-of-the-box. Next.js is built on top of React and provides developers with an efficient way to manage performance, SEO, routing, and deployment complexities without needing complex configurations.
Server-Side Rendering (SSR)
- SSR in Next.js allows React components to be rendered on the server before sending the final HTML to the browser. This can significantly improve SEO (since search engines can crawl pre-rendered HTML) and performance (by reducing the initial page load time).
- Instead of rendering an empty page followed by a JavaScript-rendered app (like in traditional client-side rendering), SSR allows the user to see fully rendered content as soon as the page loads.
- SSR is achieved using the
getServerSideProps
function.
export async function getServerSideProps() {
const data = await fetchSomeData();
return {
props: { data },
};
}
Static Site Generation (SSG)
- SSG is another rendering method where HTML pages are generated at build time. The static pages can then be served directly to the client without the need for server processing on each request.
- Next.js uses the
getStaticProps
function to fetch data at build time. - Next.js also supports Incremental Static Regeneration (ISR), where static pages can be regenerated in the background at runtime when the data changes, without needing a full rebuild of the site.
export async function getStaticProps() {
const data = await fetchSomeData();
return {
props: { data },
};
}
Hybrid Rendering (SSR + SSG)
- Next.js allows us to combine both SSG and SSR in the same application, meaning some pages can be statically generated while others can be rendered on the server per request. This flexibility makes Next.js an ideal choice for hybrid applications.
API Routes
- Next.js comes with a built-in API routing system that allows developers to create serverless functions or API endpoints alongside their web app.
- These API routes can be used to handle requests (e.g., form submissions, database queries, etc.) without needing an external server or setting up Express.js.
- API routes are created inside the
pages/api/
folder.
export default function handler(req, res) {
res.status(200).json({ message: 'Hello from API route!' });
}
File-Based Routing
- Next.js offers a file-based routing system, meaning the structure of the
pages
folder directly corresponds to the app’s routes. - For example:
pages/index.js
→/
(homepage)pages/about.js
→/about
pages/blog/[id].js
→/blog/:id
(dynamic routes)
- No additional configuration is required to define routes.
Leave a Reply