Domanda

I'm using ReactJS (React Hooks, specifically) to build an application. Part of that application involves account creation, sign-in, and authentication. I only recently finished the sign-in feature, and I noticed that while all my components have access to the JWS/JWT, only my SignIn component has a state for whether you're actually signed in or not (because of course, the JWT may be invalid or expired, so "has a JWT" doesn't mean "is currently signed in").

In thinking about how best to get that status out to the rest of my app, I realized I have at least two options, and I'm not sure which is best. Maybe someone here can advise me :)

Option 1: I lift the sign-in state up to the main App component, since most of the app will need to know that state at some point, and then pass it down through every component via props. I know "lift state up" is a common mantra, but it feels a little excessive to have it on the main App container and passed to every component through props.

Option 2: Since I already have an AuthHelper object that I'm exporting/importing, I could have the AuthHelper keep track of the signed in state, and allow components to subscribe to SignInStateChange events that the AuthHelper triggers. Very pub-sub. I'm not averse to this, but I know pub-sub is controversial, so I'd like some opinions before I decide to definitely do this.

I suppose there's also Option 3: Redux, but for now this is the only state variable that needs to be global, so I don't want to over-engineer a solution to it just yet.

So which is the better approach: having an App-level state passed down through props, or using a pub-sub technique with an exported/imported helper object?

È stato utile?

Soluzione

This sounds like a perfect fit for useContext() which is made to avoid passing props multiple levels down.

Basicaly make a context

const MyContext = React.createContext({something: 1})

Then make sure the there a provider in the dom

const App = props => <MyContext.Provider><SomeOtherComponents/></MyContext.Provider>

Then several levels deep you can get a reference to the context by using

const context = useContext(MyContext)
context.something //1
Autorizzato sotto: CC-BY-SA insieme a attribuzione
scroll top