How to use Recoil Selectors in Nextjs

How to use Recoil Selectors in Nextjs

·

2 min read

Welcome 👋, to this new blog post where I will teach you how you can use selectors in recoil for state management.

🤔Difference between Atoms and Selectors

Atoms are used to store a value. But selectors are used to getting or setting the value of an atom. In simple words, selectors help you perform complex logic for your website.

😁Situation

Let’s suppose I give you a project of making a currency converter. In this project, you need to have two inputs US dollars and Rupee. But the problem is how will you convert the US dollars to Rupee in recoil so that you can use values globally.

💡Solution

We can use selectors here. But how?

Step1: Setup your recoil. Recoil State Management in Nextjs

Step2: Now make a new atom called usdAtom

import { atom } from "recoil";

export const usdAtom = atom<number>({
  key: "usd",
  default: 1,
});

Then come to your index.tsx file

Step3: Now make a new selector called rupeeSelector

import { usdAtom } from "./../atoms/atoms";
import { selector } from "recoil";

export const exchangeRate = 0.013;

export const rupeeSelector = selector<number>({
  key: "rupee",
  get: ({ get }) => {
    // get is similar to useRecoilValue
    const usd = get(usdAtom);

    const newValue = usd / exchangeRate;

    return newValue;
  },
  set: ({ set, get }, newValue) => {
    const returnableValue = Number(newValue) * exchangeRate;

    set(usdAtom, returnableValue);
  },
});

Now you can enjoy the values

import type { NextPage } from "next";
import Head from "next/head";
import Image from "next/image";
import { useRecoilState } from "recoil";
import { usdAtom } from "../atoms/atoms";
import { rupeeSelector } from "../selectors/selectors";

const Home: NextPage = () => {
  const [usd, setUSD] = useRecoilState(usdAtom);

  const [rupee, setRupee] = useRecoilState(rupeeSelector);

  return (
    <div className="flex min-h-screen flex-col items-center justify-center py-2">
      <div className="flex flex-col">
        {/* dollars */}
        <label htmlFor="">Dollars</label>
        <input
          type="number"
          placeholder="Please enter the dollars amount"
          className="input"
          value={usd}
          onChange={(e) => {
            setUSD(Number(e.target.value));
          }}
        />

        {/* Ruppee */}
        <label htmlFor="" className="mt-4">
          Rupee
        </label>
        <input
          type="number"
          placeholder="Please enter the Ruppes amount"
          className="input"
          value={rupee as number}
          onChange={(e) => {
            setRupee(Number(e.target.value));
          }}
        />
      </div>
    </div>
  );
};

export default Home;

Whole Code: GitHub - nextdev1111/selectors

Did you find this article valuable?

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