https://github.com/pie6k/use-needed-state
It's like `useState` - but it'll spy what part of the state is actually used during the render and re-render only if needed.
https://github.com/pie6k/use-needed-state
Last synced: 2 months ago
JSON representation
It's like `useState` - but it'll spy what part of the state is actually used during the render and re-render only if needed.
- Host: GitHub
- URL: https://github.com/pie6k/use-needed-state
- Owner: pie6k
- License: mit
- Created: 2020-04-01T08:43:39.000Z (about 5 years ago)
- Default Branch: master
- Last Pushed: 2020-04-01T08:53:32.000Z (about 5 years ago)
- Last Synced: 2025-02-14T17:02:19.443Z (3 months ago)
- Language: TypeScript
- Homepage:
- Size: 10.7 KB
- Stars: 2
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# use-needed-state
It looks the same as regualr `useState`, but it'll watch what parts of state were actually used during the render.
So even if you'll update using 'setState', but parts used during the render did not change (are equal) - it'll skip re-render
## example
We'll create simple component with state that is object with 2 values.
One is 'loggedUserName' which is some string, and another is 'showLoggedUserInfo' which is boolean indicating if we want to show logged user name or no.
If 'showLoggedUserInfo' is false - we're not even accessing user name during the render.
It means that when user name will change while we're not showing it - we don't have to re-render and this is exactly what will happen.
```tsx
import React from 'react';
import { useNeededState } from 'use-needed-state';interface AppInfo {
loggedUserName: string;
showLoggedUserInfo: boolean;
}function SomeComponent() {
/**
* Initialize state the same way as with `useState`
*/
const [appInfo, setAppInfo] = useNeededState({
// name of our user
loggedUserName: 'Bob',
// indicator telling if we want to show logged user name
showLoggedUserInfo: false,
});/**
* If `showLoggedUserInfo` is false - we'll not even use
* logged user name during the render, so we "dont care" what it is
* It means that if loggedUserName will change - we don't have to
* re-render as it'll not impact the result of rendering
*/
if (!appInfo.showLoggedUserInfo) {
return (
Hello!
{/* if we'll change user name while `showLoggedUserInfo` is false - component will not re-render */}
Change user name
Toggle show user info
);
}/**
* If showLoggedUserInfo is true - we're actually accessing user name
* so now component will re-render if it's changed in the state
*/
returnHello, {appInfo.loggedUserName}!;function changeUserName() {
const newName = window.prompt('New name');setAppInfo((state) => {
return { ...state, loggedUserName: newName };
});
}function toggleShowUserInfo() {
setAppInfo((state) => {
return { ...state, showLoggedUserInfo: !state.showLoggedUserInfo };
});
}
}
```