by rtpg · 7y ago · 0 comments
It really feels like if there was some way to put this really dirt-simple counter code into a plain-Jane Javascript object then a lot of this hand-wringing about state management in React goes away (contexts are an interesting little solution to things though)
What I tell my students is that you want to think of your app in three layers -- the data layer (Redux/data fetching), the glue layer (@connected components, useEffect hooks), and the presentational layer. The representational layer should be just your rendering logic and the data layer should deal with fetching/storing/updating data. The two should never interface directly, only through your container "glue" components.
I do think you can have a hook return a javascript object though for the normal reasons of encapsulation and such.
export function counterView (count) {
return <span>{ count }</span>
}
export function Counter () {
const [count, setCount] = useState(0)
// … useEffect to setInterval count or whatever
return counterView(count)
}
At this point, though the question becomes is this pattern buying you anything? Pure view functions should be easier to test, but React testing library's act() tool looks like it isn't that much more painful to just test the full component. Similarly, pure view functions are potentially easier to reuse with different "component logic", but I'm unsure how often that would be the case.It's maybe a bit clearer as a pattern where the "stateful" and "stateless" stuff may be than mixing the two, and certainly seems like it might help make it easier to follow the "Hook rules" (most of your loops and conditionals should be inside the "pure" function). But it's potentially also just a source for extra noise/boilerplate.
Like I said, I'm still thinking about it, and something I expect to explore in an actual codebase at some point.