How to persist React states after a refresh?! ( Part 2)

Adel Benyahia
2 min readOct 22, 2022

React is a popular library that makes developer life easier. It provides a variety of powerful APIs to manage all our apps.

To store and manage variables in react, we will use Recoil

Recoil lets you create a data-flow graph that flows from atoms (shared state) through selectors (pure functions) and down into your React components. Atoms are units of state that components can subscribe to. Selectors transform this state either synchronously or asynchronously.

Create an Atom at ./src/recoil/atom.js

const Count= atom({
key: 'Count',
default: 0,
});

Atoms need a unique key, which is used for debugging, persistence, and for certain advanced APIs that let you see a map of all atoms.

then we have to wrap our <App> component with <RecoilRoot> in ./src/index.js

import { StrictMode } from "react";import { createRoot } from "react-dom/client";import { RecoilRoot } from "recoil";import App from "./App";const rootElement = document.getElementById("root");const root = createRoot(rootElement);root.render(<StrictMode>  <RecoilRoot>
<App />
</RecoilRoot>
</StrictMode>);

Now <Counter> component:

import React from “react”;import { useRecoilState } from “recoil”;import { Count } from “./recoil/atom”;export default function Counter() {const [count, setCount] = useRecoilState(Count);const increaseCount = () => {return setCount(count + 1);};const decreaseCount = () => {return setCount(count — 1);};return (<div>  <h1> Count {count} </h1>
<button onClick={increaseCount}>+</button>
<button onClick={decreaseCount}>-</button>
</div>
);}

As you can see its now more cleaner; we have removed the useEffect and useState hooks and replaced them only by one useRecoil hook

this example we have a state with a name “count”, the value of this count state will be increased and decreased by clicking two buttons (using the “setCount” function).

All working good 👍…

Check out your DevTools

Now check this working example in codesandbox

Learn more

--

--

Adel Benyahia

Web application developer (HTML │ CSS │ JS | ReactJS | NextJS | NestJS | MERN)