-
-
Notifications
You must be signed in to change notification settings - Fork 810
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Adding example for react using hooks #159
Conversation
This helps to understand how to use nanoid in react with hooks.
Am I right, that What do you think about this way to use Nano ID with hooks? const key = useMemo(nanoid) |
@ai in this case nanoid is called on every render too unless you specify dependencies list. And still useMemo is not stable. It works only for pure computations. React may drop cache any time. These are ways to go. const useNanoid = () => {
const ref = React.useRef(null)
if (ref.current == null) {
ref.current = nanoid();
}
return ref.current;
}
const Component = () => {
const id = useNanoid()
} const Component = () => {
const [id] = React.useState(() => nanoid());
} |
I put a small example on place https://codesandbox.io/s/nanoid-with-hooks-yv1u5 |
Did you save it? I don't see any nanoid usage. |
@TrySound sorry my bad is there now. |
@nahumzs OK, seems like |
|
|
ref has a problem with calling Nano ID on every component render. It didn't change the ID, but use CPU. |
Thanks for improving docs :) |
This helps to understand how to use nanoid with react hooks.