Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use static variables with react hooks

With const [open, setOpen] = useState(false) I can create a variable open which is persisted over calls of a functional component.

But which hook can I use if I do not want a rerender when setting a variable?

I have a custom hook draft:

const useVariable = (initialValue) => {
  const ref = useRef();


  return useMemo(() => {
    ref.current = [initialValue, (newValue) => { ref.current[0] = newValue }]
  }, [])
}

But according to https://reactjs.org/docs/hooks-reference.html#usememo I can not rely that useMemo is not called anytime again.

like image 584
velop Avatar asked Mar 01 '19 12:03

velop


People also ask

Does React Hooks work with static typing?

Do Hooks work with static typing? Hooks were designed with static typing in mind. Because they're functions, they are easier to type correctly than patterns like higher-order components. The latest Flow and TypeScript React definitions include support for React Hooks.

Can React Hooks take parameters?

Basically, what this hook does is that, it takes a parameter with value true or false and toggles that value to opposite. It's useful when we want to take some action into it's opposite action, for example: show and hide modal, show more/show less text, open/close side menu.

When should you not use a hook on a React?

1. Changing the Hooks Invocation Order. Hooks should not be called within loops, conditions, or nested functions since conditionally executed Hooks can cause unexpected bugs. Avoiding such situations ensures that Hooks are called in the correct order each time the component renders.

Are React Hooks still used?

React hooks have been around for some time now, yet many React developers are not actively using them.


2 Answers

You can make use of useRef hook if you just want to store the some data in a variable and not re-render when the variable is set

const unsubCallback = useRef(null);

if(!unsubCallback) {
    unsubCallback.current = subscribe(userId)
}
like image 88
Shubham Khatri Avatar answered Oct 02 '22 23:10

Shubham Khatri


Thank to @shubham-khatri I found a solution to my question. Just use the initialValue of the useRef hook:

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

https://codesandbox.io/s/v3zlk1m90

Edit: To account for Christopher Camp's comment I added that also a function can be passed like in useState. See usage in codesandbox

like image 37
velop Avatar answered Oct 02 '22 22:10

velop