Learn React & Material UI - #15 Context API (React 16.3+)
Hello folks, I didn't intend to cover this topic at first, but after countless requests from you I decided to give it a go. In this video, I will introduce you to context API in React 16.3, as well as explain the state management conundrum that it aims to solve. We will then refactor our exercise database app to consume context instead of passing props.
Let's brush up on the basic notions of state and props before we move on to advanced topics. In a React app, you have container components that encapsulate state and pass it down to child components, as well as presentational components, which are often pure functions that receive read-only props and render them to the UI. Components communicate through a top-down or unidirectional data flow, meaning that a parent sends down its data down to a child, and a child can talk back by invoking functions on the parent. Shared state is lifted up to the closest parent, so that sibling components can stay in sync with each other, as well as their parent.
This waterfall approach however doesn't scale well beyond simple toy apps. In data-intensive apps with rich UIs, components branch out in multiple sub-trees, and if shared state resides up in the root component, how does a leaf node deep down the tree get its portion of data? The longer the tree, the more hoops its props need to jump through to reach their destination. After a while, it not only becomes tedious, but also redundant to pass down the props through the entire component tree.
Redux, Flux, Reflux, MobX, and many other community libraries were developed to tackle this problem. Although they do centralize the state and provide systematic means to consume and/or mutate it anywhere within the app, they do come at the price of increased complexity and boilerplate code. A relatively simple app can quickly turn into a heavy beast with Redux. If your front-end interacts with an API (which it most certainly does), then you need to preoccupy yourself with either Thunks, Saga, or RxJS to orchestrate async actions (as if Redux alone doesn't make it complicated enough). For these and other reasons, Dan himself suggests that Redux isn't a silver bullet for every situation https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367
What about small to mid-sized apps that still need to manage global state, perhaps alongside Firestore or Apollo GraphQL, yet seek to avoid the overhead that comes with state management libraries? How do you communicate the logged in user object or the language locale down the tree?
For these cases, the new React context can be a good fit. Context offers a way for child components to consume data without passing it down through props. The application data still lives in the state, and the Provider-Consumer components simply provide convenient means to distribute, subscribe, and modify that data. More on that in the video.
Note that this video unlike others in the playlist doesn't touch on Material UI. We will however apply context to our existing project, so it only made sense to to keep it in this series.
Context API in React 16.3.0 https://reactjs.org/blog/2018/03/29/react-v-16-3.html#official-context-api
More on context https://reactjs.org/docs/context.html
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Learn React & Material UI - #15 Context API (React 16.3+)», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.