next-js-recoil

How to use Recoiljs in Next.js Framework.

Recoil: An Experimental State Management Library for React

Interesting not only because it comes from Facebook, but because there’s a pretty good 20-minute talk about it and it follows the latest React standards out of the box.

Recoil

A state management library for React

Minimal and Reactish

Recoil works and thinks like to React. Add some to your app and get a fast and flexible shared state.

Data-Flow Graph

Derived data and asynchronous queries are tamed with pure functions and efficient subscriptions.

Cross-App Observation

Implement persistence, routing, time-travel debugging, or undo by observing all state changes across your app, without impairing code-splitting.

The first step is, you have to install the recoiljs library via npm or yarn

npm i recoil

// Or if you're using yarn

yarn add recoil

Then open the _app.js file from /pages folder and import the library and setup like below

import { RecoilRoot } from "recoil";

const MyApp = ({ Component, pageProps }) => {
  return (
    <RecoilRoot>
      <Component {...pageProps} />
    </RecoilRoot>
  );
};

export default MyApp;

Then create a helper file on any of your directory, the recoil helper file like below

import { atom, selector } from 'recoil'

export const countState = atom({
  key: 'count',
  default: 0,
})

export const incrementCount = selector({
  key: 'incrementCount',
  set: ({ set }) => set(countState, (currCount) => currCount + 1),
})

export const decrementCount = selector({
  key: 'decrementCount',
  set: ({ set }) => set(countState, (currCount) => currCount - 1),
})

Then in the component write codes staff like below

import { useRecoilValue, useSetRecoilState, useResetRecoilState } from 'recoil'
import { countState, incrementCount, decrementCount } from '../recoil-helper'

const useCounter = () => ({
  count: useRecoilValue(countState),
  increment: useSetRecoilState(incrementCount),
  decrement: useSetRecoilState(decrementCount),
  reset: useResetRecoilState(countState),
})

const Counter = () => {
  const { count, increment, decrement, reset } = useCounter()
  return (
    <div>
      <h1>
        Count: <span>{count}</span>
      </h1>
      <button onClick={increment}>+1</button>
      <button onClick={decrement}>-1</button>
      <button onClick={reset}>Reset</button>
    </div>
  )
}

export default Counter

And that’s it 🙂

There are many ways to implement that but make sure you are understanding the main concept of the recoiljs.

The project repository you will find here

Happy coding 🙂