Skip to content

Instantly share code, notes, and snippets.

@dr-skot
Created February 19, 2023 03:53
Show Gist options
  • Save dr-skot/d3b508d30169b976507d8f479ec83c3a to your computer and use it in GitHub Desktop.
Save dr-skot/d3b508d30169b976507d8f479ec83c3a to your computer and use it in GitHub Desktop.
React component demonstrating the difference between useRef and useState, and its implications
import { useRef, useState } from 'react';
import { Box, Button, HStack } from '@chakra-ui/react';
export default function RefVsState() {
const [state, setState] = useState(0);
const ref = useRef(0);
console.info('----RENDER----');
return (
<Box m={10}>
<p>state counter: {state}</p>
<p>ref counter: {ref.current}</p>
<HStack mt={2} gap={2}>
<Button
mr={2}
onClick={() => {
setState(state + 1);
console.info('state after increment:', state);
}}
>
increase state
</Button>
<Button
onClick={() => {
ref.current += 1;
console.info('ref after increment:', ref.current);
}}
>
increase ref
</Button>
<Button
onClick={() => {
setTimeout(() => {
console.info('state after timeout:', state);
console.info('ref after timeout:', ref.current);
}, 3000);
}}
>
report in 3 seconds
</Button>
</HStack>
</Box>
);
// you can simulate useRef with useState(object)
// swap this for the useRef line to get the same behavior
// const [ref] = useState({ current: 0 });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment