Muhammad Fauzan (fzn0x) - Blog

When to use React Context

Screenshot 2024-08-10 025556

In this article, I will explain you when you need to use React Context.

Context are meant to share data to all components under the same context, you can even use ctx.displayName to make debug easier for each component under the same context, so when to use it?

You can use React Context whenever you have a lot of same props passing between components and they related to each other, for example when you have a modal that contains many nested childs as a step, you will need the same props before you reach the step completion.

In this case, re-render will not be a problem, since you need re-render to happen so you don't need to go back to previous steps only to change some data.

So the right time to use React Context is in feature that needs to trigger to use and independent, for example Create Data Modal with complex steps, or users registration steps, anyway the important things you need to remember when you use React is the fact that re-render will happen every context or state changes.

I'm not a big fan of state libraries, mainly I just use React Context, atom or setState({ ...state, [name]: value }), adding new libraries only to adds simplicity when you can make it simple without libraries is a bit off for me.

Sometimes I found a State Engineer that shares about using state libraries or react-hook-form to make their code easier and avoid re-renders, but actually it depends on the usecase, sometimes you still need re-renders, that's why react-hook-form creating an API called useWatch or form.watch to avoid similar State Engineers.