UNPKG

rerender-react

Version:

Easy handling of object state updates in React components

119 lines (80 loc) 2.4 kB
# 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**: react-refresh@0.1.0 ## Features - `RefreshProvider` component to wrap parts of your app. - `useRefresh` hook to access a `refresh()` function. - Calling `refresh()` forces a re-render of all components under the provider. ## Installation ```bash npm install react-refresh # or yarn add react-refresh ``` ## Usage Wrap your application (or any subtree) with `RefreshProvider`: ```tsx 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: ```tsx 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 }` – Call `refresh()` 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 ```bash git clone <repo-url> cd react-refresh npm install npm run build npm test ``` ### Build ```bash npm run build ``` ### Test Tests are written using Jest and `react-test-renderer`. ```bash npm test ``` ## License MIT