I am trying to access and update the state of an object from two seperate files, i can change it if i use a local useState for each files but that is not going to work,
I have tried many different solutions, using custom hooks and local state but none of them fix my problem, i have been stuck on this issue for ~5 hours and it is driving me crazy, any help would be appreciated.
I think the problem is that i am trying to call the hook from inside a return statement, but i cannot think of any alternatives to doing this as that is where it is being rendered.
information.js:
<button class="active" onClick={() => useSetHero(hero)}>
hero.js:
export const useSetHero = (newHero) => {
const UpdateHero = () => {
const [hero, setHero] = useState(newHero);
setHero(newHero);
};
return { UpdateHero };
}
the error message i am currently getting is:
React Hook "useHero" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function
2
Answers
Define the state for the hook itself, not for a function within the hook. For example:
Additionally, note the difference between
initialHero
andnewHero
here. The former is used when first calling the hook, to initialize the first state value:And the latter is used when calling
UpdateHero
to update it to a new value:Note in the above lines that you don’t invoke a hook directly in the markup. Hooks are invoked early in the component (and always the same hooks in the same order on every render). Data and/or functions returned by the hook can then be used later.
A couple notes:
hero
here. I imagine the hook would want to return that value as well so it can be used.UpdateHero
is superfluous here, you can just returnsetHero
.I’m assuming both of these are because this is a very minimalized example of what you’re trying to do and the actual hook does more than this. But otherwise, the hook shown as is could be simplified to:
To update a useState value from a separate file in ReactJS, you would typically need to pass down a function that can modify the state value as a prop to the separate component or file. This is often done using props and callbacks. Here’s a general approach:
Assuming you have a component in one file (let’s call it ComponentA.js) where you’ve defined a state using useState:
In a separate file (let’s call it AnotherComponent.js), you can then use the passed down updateCount function to modify the state in ComponentA:
Here, when the button in AnotherComponent is clicked, it calls the handleUpdate function, which in turn calls the updateCount function passed down from ComponentA. The updateCount function uses the functional update pattern to modify the state based on the previous state.
Hope this helps