Recoil State Management in Nextjs

Recoil State Management in Nextjs

·

2 min read

Welcome 👋 guys, to this new tutorial blog post. In this blog post, I will teach you how to do state management in the nextjs with the help of recoil.

Atoms

In this tutorial, I will teach you how to use atoms from recoil in nextjs.

Think of atom-like a news report, whose work is to take news from one area to the whole nation.

🫠Situation

Let’s suppose, today you have to build a modal for your website. An example of a modal is shown 👇

But how will you make it?

We can use useState hooks for that, but useState will not be efficient for this purpose. So, you need to use Recoil in this situation.

Step1: Download Recoil

yarn add recoil

Step2: Go to the _app.js file and wrap components with RecoilRoot:

import "../styles/globals.css";
import type { AppProps } from "next/app";
import { RecoilRoot } from "recoil";

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <RecoilRoot>
      <Component {...pageProps} />
    </RecoilRoot>
  );
}

export default MyApp;

Step3: Make a atoms folder in the root directory. Then make a atoms.ts file in that folder.

Step4: Make atom for modalSwitch:

import { atom } from "recoil";

export const modalEnabledAtom = atom({
  key: "modalEnabled", // all the atoms in recoil have their unique key
  default: false, // this is the default value of an atom
});

Step5: Use this atom in modal.tsx for making modal functional.

import React from "react";
import { useRecoilState } from "recoil";
import { modalEnabledAtom } from "../atoms/atoms";

function Modal() {
  const [open, setOpen] = useRecoilState(modalEnabledAtom);

  return (
    <>
    {/*  */}
      {open && (
        <>
          <p>Modal</p>
        </>
      )}
    </>
  );
}

export default Modal;

Step6: Use this atom in index.tsx for making modal functional.

import type { NextPage } from "next";
import Head from "next/head";
import Image from "next/image";
import { useState } from "react";
import { useRecoilState } from "recoil";
import { modalEnabledAtom } from "../atoms/atoms";
import Modal from "../components/Modal";

const Home: NextPage = () => {
  const [open, setOpen] = useRecoilState(modalEnabledAtom);

  return (
    <div className="flex min-h-screen flex-col items-center justify-center py-2">
      <button className="p-2 bg-red-500" onClick={(e) => setOpen(!open)}>
        Open
      </button>

      <Modal />
    </div>
  );
};

export default Home;

Now you can try it

If any error comes, feel free to join the discord server: https://discord.gg/hN4Wc5VR4M

Thanks for reading this blog post.

Did you find this article valuable?

Support Next Dev's Blog by becoming a sponsor. Any amount is appreciated!

Â