Next Js just killed React hooks

web3vicky

Vignesh Murugan

Posted on June 18, 2024

Next Js just killed React hooks

If you've used React hooks like useState() and useEffect() just like me, then the approach Next Js brought can be quite surprising and confusing to you. But trust me once you got hold of this concept you're gonna love it. 

It's React's way to use hooks like useState and useEffect to fetch data from the server and render it in a browser whenever a component mounts on the page. 

This traditional approach is quite ineffective when it comes to components that are not going to be interactive on the client side. 
You might've sensed what I'm trying to talk about, if not it's about the Server Side Rendering(SSR) or Server components introduced by Next Js. 

Two important issues Next Js fixes here:

  1. SEO optimization
  2. Waterfall problem

Talk is cheap, show me the code

Enough of the talk, let me walk you through the code that gets the work done.
First, let's see how React handles data fetching and rendering.

React Code:

import axios from "axios";
import { useState, useEffect } from "react";

export default function UserCard() {
  //useState hook for state management
  const [user, setUser] = useState({});

  // useEffect hook for data fetching
  useEffect(() => {
    axios
      .get("https://jsonplaceholder.typicode.com/users/1")
      .then((response) => {
        setUser(response.data);
        console.log(response.data);
      });
  }, []);

  return (
    <div className="flex items-center justify-center h-screen">
      <div className="flex flex-col justify-center items-center border-2 p-4 rounded-lg">
        <p>
          <span className="font-bold">Name: </span>
          {user?.name}
        </p>
        <p>
          <span className="font-bold">Email: </span>
          {user?.email}
        </p>
        <p>
          <span className="font-bold">City: </span>
          {user?.address?.city}
        </p>
        <p>
          <span className="font-bold">Company: </span>
          {user?.company?.name}
        </p>
      </div>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

The above code is for a UserCard React component which we render on the client side.

Output:

react code output

Here's how the process works in React:

  1. The UserCard component is rendered initially.
  2. The useEffect hook runs because of the empty dependency array [], meaning it will only run once when the component mounts.
  3. Inside useEffect, an HTTP GET request is made using Axios to fetch user data from the specified URL (https://jsonplaceholder.typicode.com/users/1).
  4. Once the response is received, the setUser function is called with the fetched user data, updating the state.
  5. As a result of the state update, the component re-renders with the updated user data.

explanation of react hooks operation


It's time to find out what Next Js has got to offer us!

Next Js code:

import axios from "axios";

// API call with no useState and useEffect hooks
async function getUser() {
  const response = await axios.get("https://jsonplaceholder.typicode.com/users/1")
 return response.data;
}

// Function here is a Async Function
export default async function UserCard() {
  const user = await getUser();

  return (
    <div className="flex items-center justify-center h-screen">
      <div className="flex flex-col justify-center items-center border-2 p-4 rounded-lg">
        <p>
          <span className="font-bold">Name: </span>
          {user?.name}
        </p>
        <p>
          <span className="font-bold">Email: </span>
          {user?.email}
        </p>
        <p>
          <span className="font-bold">City: </span>
          {user?.address?.city}
        </p>
        <p>
          <span className="font-bold">Company: </span>
          {user?.company?.name}
        </p>
      </div>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In Next Js, every component is a Server component by default.

Server-side rendering (SSR) is a great add-on to React's arsenal, as it will improve the SEO and waterfall problem.

  1. The UserCard component will be rendered on the server side, which means the API call will be made on the server and the response data will be populated inside the component. 
  2. Next Js will send the component with all the populated data which is SEO-friendly to the client side (note: this is a server component).

React has a big issue, it's the Anti SEO pattern, but Next Js fixed it and made SSR popular. Doing the same SSR in React can be a bit tedious set up initially, but we also need to consider that Next Js is a full-stack framework.

Even though SSR might sound cool it also comes with some drawbacks like load on the server side, static components.
 
It's essential to understand the tradeoffs each approach provides and choose the one that fits your needs.

Follow me for more awesome tech contents!
LinkedIn | Twitter

💖 💪 🙅 🚩
web3vicky
Vignesh Murugan

Posted on June 18, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related