Skip to content

Instantly share code, notes, and snippets.

View oney's full-sized avatar

Wan-Huang Yang oney

View GitHub Profile
function Chat({ selectedRoom }) {
const theme = useContext(ThemeContext);
const onConnected = useEvent(async connectedRoom => {
showToast(theme, 'Checking connection to ' + connectedRoom);
await checkConnection(selectedRoom);
showToast(theme, 'Connected to ' + connectedRoom);
// After await, theme is not fresh!
function Note() {
const [text, setText] = useState('');
const onTick = useEvent(() => {
count += 1; // 😩 I can't modify 'count'
saveDraft(text, count);
});
useEffect(() => {
let count = 0;
// ...
socket.on('connected', async () => {
await checkConnection(selectedRoom);
showToast(theme, 'Connected to ' + connectedRoom);
// I just want to call showToast with one line
// Why I must define a new callback with 3 lines
// of code outside of effect?? 🤨
});
import { Form } from 'antd';
// If 'submit' prop is useEvent-safe,
// antd would wrap withStable (from React.memo) internally
function Chat({onOdd, onEven}) {
const [text, setText] = useState('');
const onSubmit = () => {
sendMessage(text);
};
return <Form submit={onSubmit} />;
function Chat({onOdd, onEven}) {
const [text, setText] = useState('');
return <SendButton
onClick={text.length % 2 ? onEven : onOdd}
// 😚 SendButton won't re-render
/>;
}
const SendButton = withStable(["onClick"], ({ onClick }) => (
<button onClick={onClick}>click</button>
));
function ChatA({text}) {
const onClick = () => sendMessage(text);
// 😃 No need to do anything else
return <SendButton onClick={onClick} />;
}
function Chat({rooms}) {
const [text, setText] = useState('');
return rooms.map(room => (
<SendButton onClick={
() => sendMessage(room, text)
// 😚 No re-render and no wrapping
} />
));
}
import { withStable } from "react-with-stable";
const SendButton = withStable(
["onClick"], // list 'onClick' as stable callback
({ onClick }) => (
<button onClick={onClick}>Click</button>
)
);
function Chat() {
import { Form } from 'antd';
function Chat({onOdd, onEven}) {
const [text, setText] = useState('');
const onSubmit = useEvent(() => {
sendMessage(text);
});
return <Form submit={onSubmit} />;
// 🧐 Is 'submit' prop useEvent-safe?
}
function Chat({onOdd, onEven}) {
const [text, setText] = useState('');
return <SendButton
onClick={text.length % 2 ? onEven : onOdd}
// 🙁 React.memo fails, and it'll re-render
/>;
}