Skip to content

Instantly share code, notes, and snippets.

@macorifice
Last active March 11, 2021 10:07
Show Gist options
  • Save macorifice/d581e0fe2e9bba55361f8b5e8f037f6a to your computer and use it in GitHub Desktop.
Save macorifice/d581e0fe2e9bba55361f8b5e8f037f6a to your computer and use it in GitHub Desktop.
Getting Started Recoil - a state management library for React
import './App.css';
import logo from './logo.svg';
import {
atom,
selector,
useRecoilState,
useRecoilValue,
} from 'recoil';
const textState = atom({
key: 'textState', // unique ID (with respect to other atoms/selectors)
default: '', // default value (aka initial value)
});
const charCountState = selector({
key: 'charCountState', // unique ID (with respect to other atoms/selectors)
get: ({get}) => {
const text = get(textState);
return text.length;
},
});
function CharacterCounter() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
<TextInput />
<CharacterCount />
</p>
</header>
</div>
);
}
function TextInput() {
const [text, setText] = useRecoilState(textState);
const onChange = (event) => {
setText(event.target.value);
};
return (
<div>
<input type="text" value={text} onChange={onChange} />
<br />
Echo: {text}
</div>
);
}
function CharacterCount() {
const count = useRecoilValue(charCountState);
return <>Character Count: {count}</>;
}
export default CharacterCounter;
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import CharacterCounter from './CharacterCounter';
import reportWebVitals from './reportWebVitals';
import {
RecoilRoot
} from 'recoil';
ReactDOM.render(
<RecoilRoot>
<CharacterCounter />
</RecoilRoot>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment