How Can Men Make Women Feel Safer in an Unsafe World?

I recently wrote an article about how much solo hiking has helped improve my mental health. Getting out into nature, being surrounded by beauty, and soaking in all the health benefits of fresh air…

Smartphone

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




Centrally manage React states with Context

React context hook can help simplify the ‘props chain’ situation where we have cross-component states and need to pass them using props through several layers of components without actually needing them along the way.

Take a look at this App component which has userName

In theHome component which does not really need userName, but it has a child component, Form, which requires userName. In this case, Home component has to receive the userName from props and pass it on to Form, which could be redundant and confusing.

React context helps manage cross-component states by having a centralised place for state management, and avoiding props chain.

Create a context file in your project at your preferred path, for example, src/store/user-context.js. Note that I named the file user-context as it’ll store user data.

I will use the same example as above. We would like to pass userName from the App component to the Form component. With context provider, you only need to pass userName to the UserContext to be consumed anywhere.

In the Form component where we want to consume the userName (not stored as name in the UserContext), create a variable with the useContext() hook as in the example and access any stored value directly.

Add a comment

Related posts:

Towing Hackettstown NJ

When you find yourself in a roadside emergency, such as a flat tire, a dead battery, or a vehicle breakdown, it’s crucial to have a reliable Towing Hackettstown NJ service at your disposal. Choosing…

Who Else Still Think That Housework Is For Women?

When someone tells me they are going to visit me, I switch to a state of alert. I start looking around, I judge that the house is a mess, and I put in my head that I have one more task to do now…

Eu.

Eu sempre gostei de participar de coisas, naturalmente me envolvia aqui, depois ali, depois falava “agora não vou mais me meter, chega de estresse” e era a maior mentira que eu contava pra mim…