UNPKG

rerenderer

Version:

For React: Easy handling of object editing and state update re-renders

115 lines (78 loc) 2.35 kB
# Rerenderer for React 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. `rerenderer` provides a simple context and hook API to force re-renders on demand. ## Features - `RerenderProvider` component to wrap parts of your app. - `useRerender` hook to access a `rerender()` function. - Calling `rerender()` forces a re-render of all components under the provider. ## Installation ```bash npm install rerenderer # or yarn add rerenderer ``` ## Usage Wrap your application (or any subtree) with `RerenderProvider`: ```tsx import React from 'react'; import ReactDOM from 'react-dom'; import { RerenderProvider } from 'rerenderer'; import App from './App'; ReactDOM.render( <RerenderProvider> <App /> </RerenderProvider>, document.getElementById('root') ); ``` In any component under the provider, use the `useRerender` hook: ```tsx import React from 'react'; import { useRerender } from 'rerenderer'; type Data = { name: string; [key: string]: any }; function MyComponent({ data }: { data: Data }) { const { rerender } = useRerender(); const handleChange = () => { // Mutate object properties... data.name = 'New Name'; // Force React to re-render to pick up changes rerender(); }; return ( <div> <span>{data.name}</span> <button onClick={handleChange}>Change Name</button> </div> ); } ``` ## API ### `RerenderProvider` A React context provider that exposes the `rerender` function to its children. Props: - `children: React.ReactNode` – Components that should be able to trigger a refresh / rerender. ### `useRerender` Hook to access the `rerender()` function. Returns: - `{ rerender: () => void }` – Call `rerender()` to force a re-render of the provider's subtree. ## Limitations - Calling `rerender()` forces a full re-render of the provider's subtree; use it judiciously to avoid performance issues. ## Development ```bash git clone <repo-url> cd rerenderer 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