Hey everyone! I'm Itay, a fullstack web developer who specializes in back-of-the-frontend code, particularly with React.js. Today, I'll teach you useful code hacks to supercharge your codebase.
What you'll learn
- The flaws of the context API
- The logical wrapper factory
- The action factory
I want to introduce my common way of writing context providers, so that I can write custom components and hooks and the you‘ll understand their meaning without me having to explain too much. If you want me to do a more simple context tutorial in the future, let me know in the comments.
The Context API is the state-of-the-art way to manage state in React. It is an alternative to Redux, MobX, and a large variety of state management libraries made by the community.
Imagine having 60 auth-protected component in your app. Your codebase would be a mess!
- Messy code
- Repeating a lot of code all the time
Suppose you have a context and a ContextProvider component attached to it.
In the same component you provided the context, you want to use the context for a button, like the example below:
You wanted to do something really simple, but ended up messing up your codebase. As a workaround, you might do something like this:
But now, we are back in the repetitive tasks zone.
A component factory is a function that returns a React functional component.
() => () => <div></div>
We can use component factories to clean up our codebase and create a clean code structure. Today, I will teach you about 2 time-saving and life-saving factories: The context logical wrapper and the context action factory.
Logical Wrappers solve the problems of conditional rendering we saw in the beginning, without having to mess up your codebase. You create them with this function:
Then, our problem from before can be solved in just a few lines of code:
You can save tons of time by using this component factory for every context you create.
Context actions are high-reusable components because of the way they are built.
Now, we can create out
ComponentB with just one line of code!
Now you must ask yourselves - why would you add the className prop to your context action? The reason is simple: Reusability. The best way to demonstrate it is by example:
Do you want to see how to add icons to our action buttons? How to use TypeScript with those? Let me know in the comments below.
In the next episode, we'll discuss supercharging forms with react! Give me a follow if you want to see this.
See component factories in action (at branch 1.1.2):