DEV Community

Cover image for Using Custom Hooks in multiple React Components.
px
px

Posted on

Using Custom Hooks in multiple React Components.

For the longest time, I had a fundamental misunderstanding of how react hooks work, and I hope to correct that misunderstanding in this little rant.

What happens when a custom hook is called(multiple times)?

Using a single custom hook in more than one component essentially creates separate instances of that custom hook and the state it manages for the components that call it. So whatever one of the components do with the custom hook doesn’t affect the other. Essentially, it’s just like calling one function in more than one place in your program, the function object is essentially recreated in memory in those places it's invoked.

// UsingCustomHooks.jsx

import { useCustomHook } from "./custom-hook.js"

const FirstComponent = () => {
    const { state, setState } = useCustomHook();

    console.log(state) // Output: Burn World😈!
    setState("Hello World😁")
    console.log(state) // Output: Hello World😁
}

const SecondComponent = () => {
    const { state } = useCustomHook();

    console.log(state) // Output: Burn World😈!
}
Enter fullscreen mode Exit fullscreen mode

I think it's helpful to consider the behavior of the useState() hook in this scenario, calling the useState() hook in however many places in your app, or however many components doesn’t mean you get the same state value out of them even if all your useState() calls have the same variable names as long as they’re in their own function scopes/blocks, they don’t care about the next useState() call.

These are my 2 bits😛. Be seeing you lot!

Top comments (1)

Collapse
 
deezy profile image
DEE

Noice!