DEV Community

Discussion on: Can someone plz explain functional React Hooks ??

Collapse
peerreynders profile image
peerreynders • Edited on

Deep dive: How do React hooks really work?

Don't just read it.

Play with each example (which only requires vanilla JS - no React) until you fully understand how and why things work. Hopefully by the time you finish // Example 4, revisited you'll have the necessary Eureka moment of understanding what hooks are actually doing.

It's function component, not functional - the allusion to functional programming is misplaced especially when hooks are involved.

A function component is just a render function (similar to the render() method on the class component).

Now imagine that a component is used multiple times on the page. There is only one component (the function) but there are multiple component instances on the page (React's component (instance) tree), each one responsible for their particular part of the markup (ReactNodes, JSX) on the page.

Whenever React wants to update one of those parts it makes the "hooks environment" for that particular component instance current and then invokes the function component to render the necessary ReactNodes; the function component accesses the environment/data for the current component instance via hooks, so that it can render (and start effects) that are appropriate for the state of the current component instance.


There is this old (2015) blog post by Dan Abramov React Components, Elements, and Instances that I found helpful. It's largely about class components but it's useful to understand the role that component instances play.

"Only components declared as classes have instances, and you never create them directly: React does that for you."

Even with class components the component instance is represented by the specific set of props and the state that is managed by React separately from the object that was created from the component class.

Before hooks function components were purely driven by the props as they were generated by the owner component.

With hooks function components get access to a full component instance but again it's React that sets up the instance which the component can initialize and then later update through the lifetime of the component instance.

Collapse
himanshupal0001 profile image
Himanshupal0001 Author

Thanks for this. I will look into it.