Mr Mime
Mr Mime

Reputation: 163

Custom react hook not updating it's value

So I have the following custom hook, I want to use it to enable/disable some buttons based on various triggers inside the app.

import { useState } from 'react';

interface IDisableProps {
  buttonsDisabled: boolean;
  toggleButtons: (isDisabled: boolean) => void;
}

export default function useDisable(): IDisableProps {
  const [buttonsDisabled, setButtonsDisabled] = useState<boolean>(false);

  const toggleButtons = (isDisabled: boolean) => {
    setButtonsDisabled(isDisabled);
  };

  return {
    buttonsDisabled,
    toggleButtons,
  };
}

One of the places I'm using it from is another hook, where I declare it as

const { buttonsDisabled, toggleButtons } = useDisable(); then use it at the right moment like

if (!buttonsDisabled) {
  toggleButtons(true);
}

However, the state always remains the initial one. Upon entering with debugger in toggleButtons I see that in the local scope, this is undefined and can't see the value of buttonsDisabled. What am I missing here? Did I take the wrong approach?

Upvotes: 2

Views: 1465

Answers (2)

mfulton26
mfulton26

Reputation: 31234

From Building Your Own Hooks – React

Do two components using the same Hook share state? No. Custom Hooks are a mechanism to reuse stateful logic (such as setting up a subscription and remembering the current value), but every time you use a custom Hook, all state and effects inside of it are fully isolated.

So when you say "one of the places [you're] using it from is another hook" you are creating an additional [buttonsDisabled, setButtonsDisabled] in memory and not referencing the same state created in the other place(s) you've invoked useDisable.

Two ways to share state are 1) passing props around and 2) using Context.

Upvotes: 5

Giovanni Giampaolo
Giovanni Giampaolo

Reputation: 463

try with

const toggleButtons = useMemo(isDisabled: boolean) => {
    setButtonsDisabled(isDisabled)
}, [isDisabled]);

Upvotes: -2

Related Questions