Created
April 2, 2023 18:55
-
-
Save lejonmanen/7a1070e9290518a36e2c3941c51c34f2 to your computer and use it in GitHub Desktop.
React Recoil example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { atom } from 'recoil' | |
// The key can be any unique value | |
// Default is the initial value | |
const countState = atom({ | |
key: 'countState', | |
default: '' | |
}); | |
export { countState } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useRecoilState } from 'recoil' | |
import { countState } from './CountAtom.js' | |
const Counter = () => { | |
const [count, setCount] = useRecoilState(countState) | |
return ( | |
<div> | |
<p> Clicks: {count} </p> | |
<button onClick={() => setCount(c => c + 1)}> +1 </button> | |
</div> | |
) | |
} | |
export default Counter |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* RecoilRoot must be installed in your React app. The most convenient method is to put it in the main.jsx file. (Assuming you're using Vite to start your project.) | |
Add an import for RecoilRoot and install it as parent to <App />. | |
*/ | |
import React from 'react' | |
import ReactDOM from 'react-dom/client' | |
import App from './App' | |
import './index.css' | |
import { RecoilRoot } from 'recoil' | |
ReactDOM.createRoot(document.getElementById('root')).render( | |
<React.StrictMode> | |
<RecoilRoot> | |
<App /> | |
</RecoilRoot> | |
</React.StrictMode>, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment