Introduction to Advanced Topics
In this chapter, we'll cover some advanced topics in React, including:
- Higher-Order Components (HOCs)
- Render Props
- Context API with Hooks
- Server-Side Rendering (SSR)
- Code SplittingHigher-Order Components (HOCs)
A Higher-Order Component is a function that takes a component as an argument and returns a new component with additional props or behavior.
import React from 'react';const withLogger = (WrappedComponent) => {
return (props) => {
console.log('Props:', props);
return <WrappedComponent {...props} />;
};
};const Hello = (props) => {
return <h1>Hello, {props.name}!</h1>;
};const HelloWithLogger = withLogger(Hello);
In this example, we define a HOC `withLogger` that logs the props of the wrapped component.
Render Props
Render Props is a pattern where a component accepts a function as a prop and calls it to render its children.
import React from 'react';
const MouseTracker = (props) => {
const [position, setPosition] = React.useState({ x: 0, y: 0 });const handleMouseMove = (event) => {
setPosition({ x: event.clientX, y: event.clientY });
};return (
<div onMouseMove={handleMouseMove}>
{props.render(position)}
</div>
);
};const App = () => {
return (
<MouseTracker render={(position) => (
<h1>Mouse position: {position.x}, {position.y}</h1>
)} />
);
};In this example, we define a `MouseTracker` component that uses Render Props to render its children.
Context API with Hooks
We can use the Context API with Hooks to share state between components.
import React, { createContext, useState, useContext } from 'react';
const ThemeContext = createContext();
const ThemeProvider = (props) => {
const [theme, setTheme] = useState('light');return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{props.children}
</ThemeContext.Provider>
);
};const ThemeSwitcher = () => {
const { theme, setTheme } = useContext(ThemeContext);return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Switch theme
</button>
);
};In this example, we define a `ThemeProvider` component that uses the Context API to share the theme state.
Server-Side Rendering (SSR)
Server-Side Rendering is a technique where we render context on the server and send it to the client.
import React from 'react';
import ReactDOMServer from 'react-dom/server';const App = () => {
return <h1>Hello, world!</h1>;
};const html = ReactDOMServer.renderToString(<App />);
In this example, we use `ReactDOMServer` to render the `App` component to a string.
Code Splitting
Code Splitting is a technique where we split our code into smaller chunks and load them on demand.
import React, { lazy, Suspense } from 'react';
const Home = lazy(() => import('./Home'));
const About = lazy(() => import('./About'));const App = () => {
return (
<Suspense fallback={<div>Loading...</div>}>
<Route path="/" component={Home} />
<Route path="/about" component={About} />
</Suspense>
);
};In this example, we use `lazy` and `Suspense` to code split our application.
Here's a practice exercise:
Create a simple React app that uses Higher-Order Components, Render Props, and Context API to manage state.
Hint: Use the `withLogger` HOC, `MouseTracker` Render Props component, and `ThemeProvider` Context API component to create a simple app.