State Management in React with Context and Hooks

Rate this content
Bookmark

A lot has changed in the world of state management in React the last few years. Where Redux used to be the main library for this, the introduction of the React Context and Hook APIs has shaken things up. No longer do you need external libraries to handle both component and global state in your applications. In this workshop you'll learn the different approaches to state management in the post-Redux era of React, all based on Hooks! And as a bonus, we'll explore two upcoming state management libraries in the React ecosystem.

This workshop has been presented at React Summit Remote Edition 2021, check out the latest edition of this React Conference.

FAQ

State management in React refers to the techniques used to manage and handle data (state) across components. It involves tracking how data changes over time and ensuring that the user interface remains consistent with these changes.

React Context and Hooks are features in React for managing state and side effects in functional components. Context provides a way to pass data through the component tree without having to pass props down manually at every level, while Hooks offer a way to use state and other React features without writing a class.

The Context API is built into React and provides a simpler and more straightforward way to share state across components. Redux, on the other hand, offers a more robust solution with better tools for managing complex state logic, middleware support, and time-travel debugging.

Yes, the Context API can be used for global state management by wrapping the entire application in a Context provider, allowing any component in the app to access the state without props drilling.

The useReducer Hook is a React Hook that is used for managing state in React applications. It works similarly to the reducer in Redux, providing a more manageable way to handle complex state logic in components by dispatching actions to a reducer function.

Errors in Context API can be managed by including error handling logic within the context provider. This typically involves setting an error state and updating it in response to exceptions or API call failures, which can then be accessed by any component consuming the context.

When using the Context API, it's important to consider potential performance issues such as unnecessary re-renders. Optimizing performance can involve using memoization techniques, such as React.memo or useMemo, and ensuring that context providers are not re-rendering too frequently.

Roy Derks
Roy Derks
71 min
10 Jun, 2021

Comments

Sign in or register to post your comment.

Video Summary and Transcription

Today's workshop focuses on state management in React using the Context API and Hooks. The Context API is now a viable option for state management and provides additional features for effective state management. Custom hooks can be created to handle local state and access values from the context. Combining multiple contexts and using the useMemo hook can prevent unnecessary component rerenders. The useReducer hook allows for more complex state logic, similar to Redux. Debugging can be done by creating custom hooks and logging actions. Context can be used for global state management by separating providers into different components. The workshop includes exercises to practice using context and breakout rooms for discussion. The Q&A session covers fetching data and managing errors with context.

1. Introduction to State Management in React

Short description:

Today's workshop is about state management in React with Context and Hooks. I will show you some alternatives and how they compare to Redux. My name is Roy, you can find me on Twitter using the handle gethackteam. I'm managing engineering teams at Vandebron and working with the Sailor team. I've written books and given talks on React, React Native, and GraphQL. I recently created a book on creating full stack GraphQL applications.

Today's workshop is about state management in React with Context and Hooks. So I'm glad to see you all signed up and joined me for this workshop. So what is this about? I think if you're working with React you probably heard about state management from the beginning onwards and you probably have been confused and also reading out more about it every day because I think there are a lot of different topics in React state management.

When we started, or at least when I started working with React, I think everyone said Redux was the golden tool for state management, and often you would find at least if you were looking for a job like two or three years ago, you probably saw Redux as a desired skill for basically every company that worked at React. And also people are asking about React, so every time I did workshops people keep asking me questions about how to use Redux, how to implement it, why you should use it for state management or why not. And I think the discussion is still very relevant today. And even with new tools like the context API, it has become more and more relevant. Like, is Redux actually the best tool for your product? And should you be using it? So for today, I won't be telling you how to use Redux, but I will show you some alternatives and also how those alternatives compare to Redux.

A little bit about myself, so my name is Roy, you can find me on Twitter using the handle gethackteam, and currently I'm managing the engineering teams at Vandebron, which is a renewable energy company in the Netherlands. And I also work together with the Sailor team, and Sailor is an e-commerce API for actually more of an entire product, sort of comparable to what Strapi or GraphCMS is doing for CMSs, but then for e-commerce. It's also a really nice tool that is using a lot of React on the front end. And also you might already know me from some of the books I've written about React or React Native or talks I did about those topics, but also a lot about GraphQL, so if you're interested in that, please find me online. And also quite recently, I created this new book on creating full stack GraphQL applications, and it's both with GraphQL and TypeScript on the back end and also React and XGS on the front end, so if you're interested in those kind of things, yeah, you can find it here on this website.

2. Introduction to Context API and State Management

Short description:

Today's workshop is mostly about the context API and how you can use it to do state management effectively in any React application. The context API can be seen as sort of state or local state that wraps multiple components. You should be able to access this context value and also access functions to update the context value. Before a couple versions of React ago, it was advised not to use the context API for state management. However, a lot has changed, and now it is a viable option. The context API provides additional features that make state management more effective.

So for today, let's go back to state. And before we actually go into details, let's also look at what state actually is because state can be a lot of things, and state often can also be living just inside a menu. So I think two years ago, I was creating a nice open source library for the city of Amsterdam, so also the city where I'm living in, and over there, we were working with state, of course.

We also created a component library so in that we also worked with menus and menu items inside such a menu. And the menu looks something like this. So you would have a simple menu that could be open or it could be closed, and whether it was open, the state went through, and we decided to display a submenu. And in this solution, we almost always pass state down. So you can just create a menu, and you pass state down, whether or not the menu's open, and then based on that, you will do something inside maybe a child component, you maybe render a child component.

And in this solution, you almost always use local state, so either a state in a class-based React component, or maybe if you're using function components, then you would use the useState hook. And I think for simple things like this, like having a menu, having a submenu, or maybe just a menu item, you always choose to use local state because it doesn't really make sense to implement something bigger, like Redux or the Context API or maybe one of those other tools that are around. But if you have a more complex menu, you already need to consider if you still want to be using simple local state in React. Because maybe you have a menu, you'd have a submenu, there's a menu item, or maybe the menu item inside the submenu is another submenu, so in theory, we could go indefinitely far.

And in this solution, it's already good to start thinking about state like how complex should my state be? Or how simple should it be? Because this could be an example of your menu. So maybe you have a hamburger menu for mobile devices. It could be open or it could be closed. So you still have simple state like open is true or false. But maybe you also have a child inside that could be open or closed, so maybe you also have state for the opened or closed child in there. So this is already starting to look a bit more complex, and especially if you want people to stay in the same state whenever they refresh the page. I think it's getting more and more complex, and those are things you should think about.

And also you might be using, if you worked in a component library before, you probably have been wondering about accessible components. So if you want your component to be accessible, you want certain parts to be highlighted whenever someone uses the keyboard to navigate instead of their mouse. If you would be in such a situation that maybe you also want to know which child is selected, so you don't only want to know if the menu is opened, if a submenu is opened, or actually which submenu is opened, but you also want to know which child is selected. And it goes pretty far, and it also depends on how far you want to go, because I don't think you need to define IDs in state to determine which submenu is opened, but maybe if you do want to do this, it already gets more complex.

And this is still something you can quite easily use local state for. But there's already something you need to think about if you would still pass the prop zone. And I think for these scenarios where you would have a menu with a menu item, or maybe a menu with a submenu, or multiple submenus and menu items inside there, I think it's probably straightforward to say you could just pass state down, you create local state in the parent components, and in there you pass it down as props. And in the parent component, you will manage the local state, you will make sure that the menu items are opened or closed whether or not the actions someone is taking in your application. But what if these components aren't menus or submenus or menu items? So what if these components are your entire application or maybe even routes inside your application or components inside routes inside your entire application? If you would be in such a situation, then probably you won't be using local state anymore because you want your state to be more diverse.

And when we talk about more diverse, I always think about the chessboard. So chess has been becoming more and more popular, I think, especially with all the Netflix shows and all the cool documentaries about it. So when you think about state, you can also think about a chessboard. So do you want your state to be simple? Do you want your state to be able to pass one field by one field or one component by one component? It's actually the most basic piece in chess is, or do you want your state to be more complex? Do you want it to be able to maybe skip components or skip fields to be able to go back and forth? Is that something you want your state to do? And if that's a scenario, then you won't be helped enough by using just local state with maybe you state hook or maybe even you seducer hook. That's a scenario you probably want to do more and you actually need more.

And with that scenario, maybe you could have ended up using context API or using use reducer, but before those functions were available, you probably ended up with using something like Redux or MobX, or if you're using GraphQL, something like Apollo. And all these libraries were created because React lacked certain futures and able to do state management. Especially in able to do state management effectively. So I think the context API helped us a lot by adding these additional features and I will show you how you can use it.

So the agenda for today, we will be mostly giving you a more introduction for about 30 or 40 minutes, and afterwards, I'll be working on exercises in breakout rooms. And then during in between, we can sync to look at the exercises. So depending on how fast everyone will go today, maybe we won't be able to do all the exercises at once. Luckily, we have the Discord channel, and I think I shared it in the chat already, and Lira was also there. So if you're not in the Discord channel, then please let her know through Discord, and then she can add you to the channel, and we can discuss the exercises even after today's workshop. So today's workshop will be mostly about the context API and how you can use it to do state management effectively in any React application. And actually, before a couple versions of React ago, it was advised not to use context because if you want the application to be stable, don't use context, it's experimental.

And I think it was a really good message because a lot has been changed to the context API. And some people even still say you shouldn't use it for state management, but I think it's also a bit of a more opinionated question to ask to a lot of people. But before this React version, it was actually advised not to use React, a context API for state management. And actually React was also telling you, or at least the React documentation was telling you, if you aren't familiar with state management libraries like Redux or Mopix, don't use context and just use these libraries because they are better tested, they're built by the community and they might have a lot of features that you otherwise wouldn't have. So how does the context API work? So the context API can be seen as sort of state or local state, or doesn't necessarily have to be local state, but could be local state, that wraps multiple components. So from multiple components, you should be able to access this context value and also to access functions to update the context value.

QnA

Watch more workshops on topic

React Performance Debugging Masterclass
React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured WorkshopFree
Ivan Akulov
Ivan Akulov
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
Concurrent Rendering Adventures in React 18
React Advanced Conference 2021React Advanced Conference 2021
132 min
Concurrent Rendering Adventures in React 18
Top Content
Featured WorkshopFree
Maurice de Beijer
Maurice de Beijer
With the release of React 18 we finally get the long awaited concurrent rendering. But how is that going to affect your application? What are the benefits of concurrent rendering in React? What do you need to do to switch to concurrent rendering when you upgrade to React 18? And what if you don’t want or can’t use concurrent rendering yet?

There are some behavior changes you need to be aware of! In this workshop we will cover all of those subjects and more.

Join me with your laptop in this interactive workshop. You will see how easy it is to switch to concurrent rendering in your React application. You will learn all about concurrent rendering, SuspenseList, the startTransition API and more.
React Hooks Tips Only the Pros Know
React Summit Remote Edition 2021React Summit Remote Edition 2021
177 min
React Hooks Tips Only the Pros Know
Top Content
Featured Workshop
Maurice de Beijer
Maurice de Beijer
The addition of the hooks API to React was quite a major change. Before hooks most components had to be class based. Now, with hooks, these are often much simpler functional components. Hooks can be really simple to use. Almost deceptively simple. Because there are still plenty of ways you can mess up with hooks. And it often turns out there are many ways where you can improve your components a better understanding of how each React hook can be used.You will learn all about the pros and cons of the various hooks. You will learn when to use useState() versus useReducer(). We will look at using useContext() efficiently. You will see when to use useLayoutEffect() and when useEffect() is better.
React, TypeScript, and TDD
React Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
Paul Everitt
Paul Everitt
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
Web3 Workshop - Building Your First Dapp
React Advanced Conference 2021React Advanced Conference 2021
145 min
Web3 Workshop - Building Your First Dapp
Top Content
Featured WorkshopFree
Nader Dabit
Nader Dabit
In this workshop, you'll learn how to build your first full stack dapp on the Ethereum blockchain, reading and writing data to the network, and connecting a front end application to the contract you've deployed. By the end of the workshop, you'll understand how to set up a full stack development environment, run a local node, and interact with any smart contract using React, HardHat, and Ethers.js.
Designing Effective Tests With React Testing Library
React Summit 2023React Summit 2023
151 min
Designing Effective Tests With React Testing Library
Top Content
Featured Workshop
Josh Justice
Josh Justice
React Testing Library is a great framework for React component tests because there are a lot of questions it answers for you, so you don’t need to worry about those questions. But that doesn’t mean testing is easy. There are still a lot of questions you have to figure out for yourself: How many component tests should you write vs end-to-end tests or lower-level unit tests? How can you test a certain line of code that is tricky to test? And what in the world are you supposed to do about that persistent act() warning?
In this three-hour workshop we’ll introduce React Testing Library along with a mental model for how to think about designing your component tests. This mental model will help you see how to test each bit of logic, whether or not to mock dependencies, and will help improve the design of your components. You’ll walk away with the tools, techniques, and principles you need to implement low-cost, high-value component tests.
Table of contents- The different kinds of React application tests, and where component tests fit in- A mental model for thinking about the inputs and outputs of the components you test- Options for selecting DOM elements to verify and interact with them- The value of mocks and why they shouldn’t be avoided- The challenges with asynchrony in RTL tests and how to handle them
Prerequisites- Familiarity with building applications with React- Basic experience writing automated tests with Jest or another unit testing framework- You do not need any experience with React Testing Library- Machine setup: Node LTS, Yarn

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

A Guide to React Rendering Behavior
React Advanced Conference 2022React Advanced Conference 2022
25 min
A Guide to React Rendering Behavior
Top Content
This transcription provides a brief guide to React rendering behavior. It explains the process of rendering, comparing new and old elements, and the importance of pure rendering without side effects. It also covers topics such as batching and double rendering, optimizing rendering and using context and Redux in React. Overall, it offers valuable insights for developers looking to understand and optimize React rendering.
Building Better Websites with Remix
React Summit Remote Edition 2021React Summit Remote Edition 2021
33 min
Building Better Websites with Remix
Top Content
Remix is a web framework built on React Router that focuses on web fundamentals, accessibility, performance, and flexibility. It delivers real HTML and SEO benefits, and allows for automatic updating of meta tags and styles. It provides features like login functionality, session management, and error handling. Remix is a server-rendered framework that can enhance sites with JavaScript but doesn't require it for basic functionality. It aims to create quality HTML-driven documents and is flexible for use with different web technologies and stacks.
Everything Beyond State Management in Stores with Pinia
Vue.js London Live 2021Vue.js London Live 2021
34 min
Everything Beyond State Management in Stores with Pinia
Top Content
State management is not limited to complex applications and transitioning to a store offers significant benefits. Pinia is a centralized state management solution compatible with Vue 2 and Vue 3, providing advanced devtools support and extensibility with plugins. The core API of Pinia is similar to Vuex, but with a less verbose version of stores and powerful plugins. Pinia allows for easy state inspection, error handling, and testing. It is recommended to create one file per store for better organization and Pinia offers a more efficient performance compared to V-rex.
React Compiler - Understanding Idiomatic React (React Forget)
React Advanced Conference 2023React Advanced Conference 2023
33 min
React Compiler - Understanding Idiomatic React (React Forget)
Top Content
Watch video: React Compiler - Understanding Idiomatic React (React Forget)
Joe Savona
Mofei Zhang
2 authors
The Talk discusses React Forget, a compiler built at Meta that aims to optimize client-side React development. It explores the use of memoization to improve performance and the vision of Forget to automatically determine dependencies at build time. Forget is named with an F-word pun and has the potential to optimize server builds and enable dead code elimination. The team plans to make Forget open-source and is focused on ensuring its quality before release.
Using useEffect Effectively
React Advanced Conference 2022React Advanced Conference 2022
30 min
Using useEffect Effectively
Top Content
Today's Talk explores the use of the useEffect hook in React development, covering topics such as fetching data, handling race conditions and cleanup, and optimizing performance. It also discusses the correct use of useEffect in React 18, the distinction between Activity Effects and Action Effects, and the potential misuse of useEffect. The Talk highlights the benefits of using useQuery or SWR for data fetching, the problems with using useEffect for initializing global singletons, and the use of state machines for handling effects. The speaker also recommends exploring the beta React docs and using tools like the stately.ai editor for visualizing state machines.
Routing in React 18 and Beyond
React Summit 2022React Summit 2022
20 min
Routing in React 18 and Beyond
Top Content
Routing in React 18 brings a native app-like user experience and allows applications to transition between different environments. React Router and Next.js have different approaches to routing, with React Router using component-based routing and Next.js using file system-based routing. React server components provide the primitives to address the disadvantages of multipage applications while maintaining the same user experience. Improving navigation and routing in React involves including loading UI, pre-rendering parts of the screen, and using server components for more performant experiences. Next.js and Remix are moving towards a converging solution by combining component-based routing with file system routing.