Wednesday, January 2, 2019

Calvin Spealman: Using a React Context as a Dispatch Replacement

React Contexts are the pretty little bows of the React world.

Here's a really quick example of the kind of messy code you can cleanup by using contexts, without dragging in a larger dependency like Redux or even Flux. Starting backwards with a diff showing lines of code I was able to remove:


All the properties I was able to remove were just pass-through. The Carousel component didn't care about any of them, but it had to pass through these callbacks so the multiple TaskList components inside the carousel could invoke actions. They were removed from the Component class itself, too, since it no longer needed to pass them through.

Where did they all go?


My ActionContext removed all the need for these passthroughs by providing a single simple helper method, action(), that components rendered under it can access.


I really enjoy the pattern of passing a single callback through a context and removing what used to be lots of callback properties. Of course, I could be using a proper dispatcher from Flux or otherwise. There are certainly several alternate and more "formal" patterns to the same end.

What I like is a solution that uses less dependencies and fewer concepts, and to me feels much simpler. I'm tending towards these clean-and-simple paths for personal projects, where I want to work quicker and rely on fewer parts, but I still want architectures that feel stable and robust.

This is one way to get that balance.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...