Assets
Using the Image Component
Instead of optimizing images at build time, Next.js optimizes images on-demand, as users request them. Unlike static site generators and static-only solutions, your build times aren’t increased, whether shipping 10 images or 10 million images.
import Image from 'next/image'
const YourComponent = () => (
<Image
src="/images/profile.jpg" // Route of the image file
height={144} // Desired size with correct aspect ratio
width={144} // Desired size with correct aspect ratio
alt="Your Name"
/>
)
Metadata
Adding Head to first-post.js We haven’t added a to our /posts/first-post route. Let’s add one.
Open the pages/posts/first-post.js file and add an import for Head from next/head at the beginning of the file:
import Head from 'next/head'
Then
export default function FirstPost() {
return (
<>
<Head>
<title>First Post</title>
</Head>
<h1>First Post</h1>
<h2>
<Link href="/">
<a>Back to home</a>
</Link>
</h2>
</>
)
}
Adding CSS
Now, let’s add some styles to the Layout component. To do so, we’ll use CSS Modules, which lets you import CSS files in a React component.
Create a file called components/layout.module.css with the following content:
.container {
max-width: 36rem;
padding: 0 1rem;
margin: 3rem auto 6rem;
}
Now
import styles from './layout.module.css'
export default function Layout({ children }) {
return <div className={styles.container}>{children}</div>
}
What is React context?
React context allows us to pass down and use (consume) data in whatever component we need in our React app without using props.
In other words, React context allows us to share data (state) across our components more easily.
What is the useContext hook?
Looking at the example above, the render props pattern for consuming context may look a bit strange to you.
Another way of consuming context became available in React 16.8 with the arrival of React hooks. We can now consume context with the useContext hook.
Instead of using render props, we can pass the entire context object to React.useContext() to consume context at the top of our component.
Here is the example above using the useContext hook:
import React from 'react';
export const UserContext = React.createContext();
export default function App() {
return (
<UserContext.Provider value="Reed">
<User />
</UserContext.Provider>
)
}
function User() {
const value = React.useContext(UserContext);
return <h1>{value}</h1>;
}
Note
For many React beginners, Redux is a way of more easily passing around data. This is because Redux comes with React context itself.
However, if you are not also updating state, but merely passing it down your component tree, you do not need a global state management library like Redux.