quisido / use-force-update Goto Github PK
View Code? Open in Web Editor NEWReact Hook to force your function component to update
Home Page: https://www.npmjs.com/package/use-force-update
License: MIT License
React Hook to force your function component to update
Home Page: https://www.npmjs.com/package/use-force-update
License: MIT License
Nice package and it works like expected! I would like to ask if something like this is possible but for now, everything I tried did not work.
import Nav from './nav';
const myFunc= () => {
forceUpdate(<Nav />);
};
The problem I face that the function that runs on the click is in another component then the component that needs force-rerender, Is there any way to achieve this? Thanks
Here is codesandbox with example:
https://codesandbox.io/s/tender-noether-cnvrz
I assume this happens because React batches two state updates and because in the end state stays the same (true -> false -> true) rerender doesn't happen at all.
export default function useForceUpdate(): () => void {
const [ , dispatch ] = useState<{}>(Object.create(null));
// Turn dispatch(required_parameter) into dispatch().
const memoizedDispatch = useCallback(
(): void => {
dispatch(Object.create(null));
},
[ dispatch ],
);
return memoizedDispatch;
}
JS, but can easily be typed:
import { useRef, useState } from 'react';
// Creates an empty object, but one that doesn't inherent from Object.prototype
const newValue = () => Object.create(null);
export default () => {
const setState = useState(newValue())[1];
const forceUpdate = useRef(() => {
setState(newValue());
}).current;
return forceUpdate;
};
Rational:
First, dispatch
unclear. Looking at the history, it is a residue from when useReducer
was used, but this is no longer the case.
Then, from the docs (see note):
React guarantees that setState function identity is stable and won’t change on re-renders. This is why it’s safe to omit from the useEffect or useCallback dependency list.
So there's no need providing it as a useCallback
dependency.
Either useCallback
or useMemo
with empty dependencies ([]
- ie, one-off) is identical to useRef().current
which somehow communicates the intent better - this value will not change. Also, with useRef
, react doesn't call Object.is(old, new) each render.
Also note that in the current code we have memoizedDispatch
but because dispatch
is stable, there's no real memoization going on - useCallback
will always return the same function.
Finally, in my case, initial render could trigger dozens of forceUpdates
so a further improvement could be (I'm not actually using it because the trade-off doesn't seem to be worth it, but others may find this useful):
import { useRef, useState, useEffect } from 'react';
// Creates an empty object, but one that doesn't inherent from Object.prototype
const newValue = () => Object.create(null);
export default () => {
const setState = useState(newValue())[1];
const updatePending = useRef(false);
const forceUpdate = useRef(() => {
if (!updatePending.current) {
setState(newValue());
updatePending.current = true;
}
}).current;
useEffect(() => {
updatePending.current = false;
});
return forceUpdate;
};
wouldn't this work just as well? none of the max
nonsense.
const useForceUpdate = () => {
const [, setIt] = useState(false);
return () => setIt(it => !it);
};
This hook stopped working, No Component Updates are triggered anymore. Any chance to fix this?
After updating to latest version (1.0.7 to 1.0.10) of use-force-update, my react native app no longer works and yields the follow error:
error: Error: While trying to resolve module `use-force-update` from file `/Users/me/development/bind-react/node_modules/reactn/build/use-global.js`, the package `/Users/me/development/bind-react/node_modules/use-force-update/package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`/Users/me/development/bind-react/node_modules/use-force-update/dist/cjs/index.cjs`. Indeed, none of these files exist:
* /Users/me/development/bind-react/node_modules/use-force-update/dist/cjs/index.cjs(.native|.ios.js|.native.js|.js|.ios.json|.native.json|.json|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx)
* /Users/me/development/bind-react/node_modules/use-force-update/dist/cjs/index.cjs/index(.native|.ios.js|.native.js|.js|.ios.json|.native.json|.json|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx)
at DependencyGraph.resolveDependency (/Users/me/development/bind-react/node_modules/metro/src/node-haste/DependencyGraph.js:243:17)
at Object.resolve (/Users/me/development/bind-react/node_modules/metro/src/lib/transformHelpers.js:129:24)
at resolve (/Users/me/development/bind-react/node_modules/metro/src/DeltaBundler/traverseDependencies.js:396:33)
at /Users/me/development/bind-react/node_modules/metro/src/DeltaBundler/traverseDependencies.js:412:26
at Array.reduce (<anonymous>)
at resolveDependencies (/Users/me/development/bind-react/node_modules/metro/src/DeltaBundler/traverseDependencies.js:411:33)
at processModule (/Users/me/development/bind-react/node_modules/metro/src/DeltaBundler/traverseDependencies.js:140:31)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async addDependency (/Users/me/development/bind-react/node_modules/metro/src/DeltaBundler/traverseDependencies.js:230:18)
at async Promise.all (index 13)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.