70 %
Chris Biscardi

7guis RecoilJS: Counter

7guis, task1. Counter in regular React with useState vs a RecoilJS implementation.

Important notes here:

  • Other than some minor setup outside of our component (atom and RecoilRoot), Recoil is drop-in replacement for useState
  • This is not a good use case for Recoil. There's no reason to make this particular example share data outside of the component tree

React useState

counter-react.js
JS
import React, { useState } from "react";
export const Counter = (props) => {
const [count, setCount] = useState(0);
return (
<div>
<input readOnly value={count} />
<button
onClick={(e) => {
setCount(count + 1);
}}
>
Count
</button>
</div>
);
};

RecoilJS

counter-recoil.js
JS
import React from "react";
import { RecoilRoot, useRecoilState, atom } from "recoil";
const counter = atom({
key: "counter",
default: 0,
});
export const Counter = (props) => (
<RecoilRoot>
<CounterComponent />
</RecoilRoot>
);
const CounterComponent = (props) => {
const [count, setCount] = useRecoilState(counter);
return (
<div>
<input readOnly value={count} />
<button
onClick={(e) => {
setCount(count + 1);
}}
>
Count Recoil
</button>
</div>
);
};