Next.js data fetching useSWR or regular fetch/axios with useEffect?

Viewed 1336

I'm learning Next.js and want to show data depending on the query that a user inputs. I want to make use of the features of Next but I'm not sure if useSWR is the correct way of handling this because I couldn't find any examples of what I'm trying to do.

My code looks like this:

export default function SearchBar() {
  const [query, setQuery] = useState("");
  const [address, setAddress] = useState("");
  const fetcher = async (url) => await axios.get(url).then((res) => res.data);
  const { data, error } = useSWR(address, fetcher);

  const handleSubmit = (e) => {
    setAddress(`https://jsonplaceholder.typicode.com/todos/${query}`);
    e.preventDefault();
  };

  if (error) return <div>ERROR</div>;

  return (
    <>
      <Form onSubmit={handleSubmit}>
        <Input
          type="text"
          onChange={(e) => setQuery(e.target.value)}
          value={query}
        />
        <SearchButton type="submit">Search</SearchButton>
      </Form>
    </>
  );
}

Is this correct usage of useSWR or should I just use a normal fetch with useEffect?

1 Answers

Personally, I recommend using useSWR as it's recommended by Next.js developers; useEffect is pure react hook.

The logic of useSWR is very simple, don't need to write a lot of code. In addition, you have a lot of option params as revalidateOnRender which will be very useful in development.

Example from docs:

function Profile() {
  const { data, error } = useSWR('/api/user')

  if (error) return <div>failed to load</div>
  if (!data) return <div>loading...</div>
  return <div>hello {data.name}!</div>
}
Related