rerender-react
v0.1.0
Published
Easy handling of object state updates in React components
Downloads
12
Maintainers
Readme
React-Refresh
A utility library for handling object state updates in React components.
React's useState hook triggers re-renders when the state value changes. However, when you mutate properties of an object without replacing the whole object, React does not detect the change. react-refresh provides a simple context and hook API to force re-renders on demand.
Peer Dependency: React (>=16.8)
Package: [email protected]
Features
RefreshProvidercomponent to wrap parts of your app.useRefreshhook to access arefresh()function.- Calling
refresh()forces a re-render of all components under the provider.
Installation
npm install react-refresh
# or
yarn add react-refreshUsage
Wrap your application (or any subtree) with RefreshProvider:
import React from 'react';
import ReactDOM from 'react-dom';
import { RefreshProvider } from 'react-refresh';
import App from './App';
ReactDOM.render(
<RefreshProvider>
<App />
</RefreshProvider>,
document.getElementById('root')
);In any component under the provider, use the useRefresh hook:
import React from 'react';
import { useRefresh } from 'react-refresh';
type Data = { name: string; [key: string]: any };
function MyComponent({ data }: { data: Data }) {
const { refresh } = useRefresh();
const handleChange = () => {
// Mutate object properties...
data.name = 'New Name';
// Force React to re-render to pick up changes
refresh();
};
return (
<div>
<span>{data.name}</span>
<button onClick={handleChange}>Change Name</button>
</div>
);
}API
RefreshProvider
A React context provider that exposes the refresh function to its children.
Props:
children: React.ReactNode– Components that should be able to trigger a refresh.
useRefresh
Hook to access the refresh() function.
Returns:
{ refresh: () => void }– Callrefresh()to force a re-render of the provider's subtree.
Limitations
- Calling
refresh()forces a full re-render of the provider's subtree; use it judiciously to avoid performance issues.
Development
git clone <repo-url>
cd react-refresh
npm install
npm run build
npm testBuild
npm run buildTest
Tests are written using Jest and react-test-renderer.
npm testLicense
MIT
