Skip to content
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

useVariable hook idea #44

Closed
valoricDe opened this issue May 8, 2019 · 2 comments
Closed

useVariable hook idea #44

valoricDe opened this issue May 8, 2019 · 2 comments

Comments

@valoricDe
Copy link

As addition to the existing useRef hook I think it's useful to have a useVariable hook which mimics the semantics of useState but do not trigger a component rerender.
It can be used in any situations where useRef would be used. Like saving the changes in a variable when onChange was called on an outer component.

The useVariable hook could look like:

import { useCallback, useRef } from 'react';

const useVariable = initialValue => {
    const ref = useRef(initialValue);
    const setter = useCallback(
        param => {
            ref.current = typeof param === 'function' ? param(ref.current) : param;
        },
        [ref]
    );
    return [ref.current, setter];
};

const [variable, setVariable] = useVariable('foobar')

I would love to hear your feedback on that one

@gragland
Copy link
Contributor

gragland commented Jul 2, 2019

Thanks for the idea and sorry for the late reply! I'm a little unclear on the benefit over useRef. Is it just that you no longer have to remember that the value is stored in ref.current, as the hook just returns the value instead of the ref?

@valoricDe
Copy link
Author

In my eyes the benefit is that the return value of useVariable is structuraly the same as useState whereas the one rerenders and the other not. With this approach you can easily pass the setter function to another component without altering anything

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants