Migratory Notes 154

Social distancing is not always an option. In an LAist investigation, Yingjie Wang uncovers an epidemic of overcrowding in Chinese “boarding houses” with “toothless oversight.” Workers living in…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Using Redux for State Management

Avoid unnecessary prop drilling by maintaining a global data store.

The first time I learned Redux… I didn’t like it. My projects were getting bigger and I could see the advantage of having a place to store data globally, but setting it all up felt a bit tedious and overcomplicated.

In a large way, this was because I was using Redux the only way I had been taught, using connect and mapStateToProps. With that method, objects from the store are called in a mapStateToProps function and then added as regular props for the component. It works, but every single time I would access the store I would have to write something that looked like this at the bottom of the component:

It seemed like more work than it was worth! Just to access a few state objects would significantly lengthen my code. Additionally, it’s not the most readable or clear for other developers.

This all changed when I learned about the useSelector() hook. At the time, I was working on a personal project that I had posted on Reddit asking for suggestions. I got lucky, someone saw the mapStateToProps method I was using and suggested an alternative.

With useSelector(), you can call props from the store on one line, like this:

It’s much cleaner, and a lot easier for others to understand as well. Immediately, I went back and refactored my entire project.

Additionally, instead of a complex connect method, you can use the hook useDispatch() hook to make changes to the state as well. Once imported, it works as easily as this:

If you’ve been using connect, this simplicity is remarkable.

And that’s it! With useSelector() and useDispatch() accessing and changing the Redux store is that simple. :)

Add a comment

Related posts:

5 Different Ways To Copy List To Another In Java

When starting on working with Java more frequently because of a change of stuff to work on, I am starting to notice the little details that Java provides. One of them is about Java Collections. To be…

Are they deconstructing more than a building?

If you went to Christchurch, New Zealand after September 2010, you would be struck by the amount of change and anticipation felt amongst local residence. After going through a number of devastating…

What I gained by breaking up with hustle culture

It was something that I relied on for a long time, trying to wring money and time out of it like water droplets out of a damp rag. I felt like it was my only option, and this belief was reinforced…