Skip to content

Instantly share code, notes, and snippets.

@lejonmanen
Created April 2, 2023 18:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lejonmanen/7a1070e9290518a36e2c3941c51c34f2 to your computer and use it in GitHub Desktop.
Save lejonmanen/7a1070e9290518a36e2c3941c51c34f2 to your computer and use it in GitHub Desktop.
React Recoil example
import { atom } from 'recoil'
// The key can be any unique value
// Default is the initial value
const countState = atom({
key: 'countState',
default: ''
});
export { countState }
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
/* 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