Add useUpdate
This commit is contained in:
31
snippets/useUpdate.md
Normal file
31
snippets/useUpdate.md
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
---
|
||||||
|
title: useUpdate
|
||||||
|
tags: components,reducer,beginner
|
||||||
|
firstSeen: 2021-09-24T05:00:00-04:00
|
||||||
|
---
|
||||||
|
|
||||||
|
Forces the component to re-render when called.
|
||||||
|
|
||||||
|
- Use the `useReducer()` hook that creates a new object every time it's updated and return its dispatch.
|
||||||
|
|
||||||
|
```jsx
|
||||||
|
const useUpdate = () => {
|
||||||
|
const [, update] = React.useReducer(() => ({}));
|
||||||
|
return update;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
```jsx
|
||||||
|
const MyApp = () => {
|
||||||
|
const update = useUpdate();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div>Time: {Date.now()}</div>
|
||||||
|
<button onClick={update}>Update</button>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
ReactDOM.render(<MyApp />, document.getElementById('root'));
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user