Even/when we don’t use context directly in our projects, most popular libraries like Formik, Redux, etc do; If the library used does not have a solution to bypass the unwanted re-rendering problem, we should handle it ourselves in our components

I was faced with a big performance problem and finally due to these re-renders and solving this problem, I had to use the react. memo, react. useCallback and react. useMemo in a large number of files. I’m asking myself: What if we could get rid of the hook that caused the problem instead of adding a lot of stuff to our component?

So the answer is react-links-in-callback, which is an NPM package that lets you mount the React Hook from the callback and use its state in the callback itself.

Let’s create an index.jsx file in which we will define our components (App, Title, and Clicks)

App: This component will be the wrapper around which we will use our Context API and implement the click behavior (in each click event, we will increment the click value and the title value will remain the same)

Title and Click: Although the click component is rerendered in each click event, the title should only be rendered once. To check this behavior, we’ll define a variable countRef in Title that increments each time we re-render

The initial component looks like this

Then after 10 clicks, we can clearly see that even though the Title component itself is still the same as before (=> The Title component has been rerendered 10 times), its countRef value has changed as well.

If there is a lot of heavy computation in the Title component, this will cause performance problems, so we should fix it: the standard method is to use React. Memo, React. UseCallback, and React. But this is a time-consuming operation and increases your line of code. Instead, we can use the React-rex-In-callback package to create a clean context.

So the first step is to install it from this command line:

npm install react-hooks-in-callback

Now, to have a clean context, we can import createContext from react-links-in-callback and use it instead of the standard react.createcontext

With the new import, we don’t need to change the App components, just the consumer components (Title and Clicks) : we just need to replace useContext with useContextSelector, which will help us select only the desired state.

In the title: const title = useContextSelector((CTX) => ctx.title); Click: const clicks = useContextSelector((CTX) => CTX. Clicks);

With this change, we can now click the Increment button and see the behavior of the title component

As expected, the title component did not re-render once after 21 clicks. Now you can see how easy it is to fix this problem (no matter how big the component is, the change is to replace the standard React context with a clean one in the React-rex-in-callback package)

You can find examples here in the sandbox.