Since useAuth is taking off, I wanted to talk about the global state management technique that makes it work. You might find it useful too, or think it's obvious, I was pretty excited when it clicked :)
And when I say useAuth is taking off ...
All those libraries give you a global store to put your data, allow every component to access that state, and manage re-renders. You get some way of updating that state and life is good.
Sometimes there's extra features.
But what if you don't want to learn yet another library? You just wanna share some state between a bunch of components. What then?
The simplest approach is to put global state in your top-level component. Pass it down through props and if you want to change it, pass down some callbacks too.
Works great and gets out of hand real fast. Passing props is cumbersome and you can create a situation where every little update re-renders your entire app.
Here's a better solution 👉 You can share the
useReducer through context and access them with a hook.
I'll explain using useAuth as an example, but the same approach works for anything.
There's 3 parts to this story:
- A context provider component
- A reducer for state
- A hook providing our API
Users render the context provider somewhere close to the root of their app. Similar to a theme provider, Apollo provider, etc.
The provider feeds state from our reducer into the context. When you fire actions on the reducer, state in the context changes, and every component using the
useAuth hook re-renders with new data.
It's pretty great.
That's our context provider.
The provider initializes
auth0 using Auth0's API and configures some properties. Full version supports a bunch of config via props, overwriting defaults, etc.
useReducer to get a state object and the action dispatch function. Initialize state from local storage if you want persistence, or keep it empty to start with.
I recommend defining initial values so your code doesn't have to deal with undefineds.
Our provider renders
AuthContext.Provider and as its value uses the
dispatch function, and
This was the trick to getting different
useAuth hooks to talk to each other. Using reducer state and dispatch as the context value.
In Gatsby you use the auth provider in
gatsby-browser to wrap your entire component tree. With create-react-app this goes around your App component, with other frameworks who knows.
The higher up it renders, the more parts of your app share state.
The auth reducer takes care of state transitions. full file
If you're not familiar with reducers: it's a function that takes the current state and an action, and calculates the next state. Always returning a fresh object.
In our case the
logout actions handle the user model and cookie expiration time. Both actions also save data to local storage so it persists across page reloads.
With heavy lifting moved to the context provider and auth reducer, our
useAuth hook becomes a sort of thin wrapper and API provider. full file
The state management part of
useAuth is that
useContext call. It hooks into the context shared by
AuthProvider and gets access to the
state object and
That gives any component that uses
useAuth access to the same shared state.
You could use
useContext directly. I prefer using a custom hook because it makes your code easier to read.
What's better, doing this everywhere you want to access some shared state:
I know what I prefer :)
With a custom hook you can use
dispatch with carefully controlled values internally. Nobody needs to know what's going on. All they need to remember is your convenient API.
So that's how you can use React hooks to build powerful abstractions on top of global state shared by all.
What do you think?
Here's how it works 👇
Then get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career.
"Man, love your simple writing! Yours is the only email I open from marketers and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"
Ready to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization
Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.
Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev
By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️