Photo by Gratisography, at Pexels
Recently I came with an idea to change the app flow I am working on, It is not a big application, so I'm using context to wrap my components routes in other to share some data and states across components.
But last night, I thought. What if I replace the context for hooks and pass down those hooks from the routes? That should be faster right? In that way, I can use my hooks as HOF holding the states I need to use across the application, no more providers, no more context.
Well, I did a little experiment to confirm that the change I was going to do could be beneficial, so I created a simple condesandbox with and application holding two routes, that passes simple state value and a method that modifies that state, to both components, in one of them I called the method on a button click to change the state up in the tree, and the profiler results were this:
App with Context API
App with Hooks as HOF (passed down from the routes)
It's not a big difference but to my surprise, the context was faster that the hook! According to React docs:
“Context provides a way to pass data through the component tree without having to pass props down manually at every level.”
Context beats Hooks as a single source of truth or HOF to manage your app state.
I'll need to test this out with more children components in other to check if the performance remains on the context side.