Preface React Context is a commonly used state management mechanism provided by React to developers. Context can effectively transfer the same state in multi-level components, and can automatically notify each component to update when the status is updated. So how does React Context do this, and why does it need to be so designed? Why do you need Context in React's concept of data management, it has always followed the concept of individual data flow and data invariance. When we need to pass the state from the parent component to the child component, we often need to pass it explicitly through Props, for example: const Father:FC = () => { const [count, setCount] = useState<number>(0) return ( <Son count={count} /> ) } const Son:FC = (props) => { const { count } = props; return ( <span>{count}</span> ) } but what if the parent component needs to pass the state to the child component of the child component, that is, the descendant component? Or does the parent component need to be passed to multiple child components at the same time? Of course, continue to use props for layer-by-layer display transfer can certainly achieve this requirement, but that kind of code is too cumbersome and difficult to maintain, if you can maintain a global variable similar to that in Js in the parent component, wouldn't it be nice for all child components to use this global variable? Yes, that's what Context is for, but it's much more than that. What is Context? Context provides a way to pass data between component…

May 23, 2023 0comments 1333hotness 0likes Aaron Read all