From e90d2a71c957870e6c28e83b303e566bc739211c Mon Sep 17 00:00:00 2001 From: Morgante Pell Date: Sun, 2 Apr 2023 23:01:51 -0400 Subject: [PATCH] feat: add a simple Recoil.js pattern --- .grit/.gitignore | 2 +- .grit/patterns/Recoil.md | 109 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 110 insertions(+), 1 deletion(-) create mode 100644 .grit/patterns/Recoil.md diff --git a/.grit/.gitignore b/.grit/.gitignore index cc720303..799e2c72 100644 --- a/.grit/.gitignore +++ b/.grit/.gitignore @@ -1,2 +1,2 @@ -engine.log .gritmodules +*.log diff --git a/.grit/patterns/Recoil.md b/.grit/patterns/Recoil.md new file mode 100644 index 00000000..4fe08986 --- /dev/null +++ b/.grit/patterns/Recoil.md @@ -0,0 +1,109 @@ +# Migrate to Recoil.js + +(Alpha) Replaces raw React state management (via `useState`) with Recoil.js. + +```grit +language js + +// This pattern is just a prototype. It's not ready for production. + +// Look at each file as a whole +Program(body=$body) where { + // Start an array of new atoms to add + $atoms = [] + $body <: contains bubble($atoms) `const [$val, $set] = $useState($initial)` where { + $atom = s"${val}State" + $atoms = [...$atoms, `const $atom = atom({ + key: $val, + default: $initial + })`] + $useState <: `useState` => `useRecoilState` + $initial => Identifier(name=$atom) + } + InsertAfterImports($atoms) +} +``` + +## Simple useState + +```js +import React, { useState } from "react"; + +const Counter = () => { + const [count, setCount] = useState(0); + const [name, setName] = useState(""); + + const increment = () => { + setCount(count + 1); + }; + + const decrement = () => { + setCount(count - 1); + }; + + const handleNameChange = (event) => { + setName(event.target.value); + }; + + return ( +
+

{name || "Counter"}

+

Count: {count}

+ + +
+ + +
+
+ ); +}; + +export default Counter; +``` + +```js +import React, { useState } from "react"; + +const countState = atom({ + key: count, + default: 0 +}); + +const nameState = atom({ + key: name, + default: "" +}); + +const Counter = () => { + const [count, setCount] = useRecoilState(countState); + const [name, setName] = useRecoilState(nameState); + + const increment = () => { + setCount(count + 1); + }; + + const decrement = () => { + setCount(count - 1); + }; + + const handleNameChange = (event) => { + setName(event.target.value); + }; + + return ( +
+

{name || "Counter"}

+

Count: {count}

+ + +
+ + +
+
+ ); +}; + +export default Counter; +```