28. What is React context and how do you use it?

What is React context and how do you use it?

React context provides a way to pass data through the component tree without having to pass props down manually at every level. It is designed to share data that can be considered 'global' for a tree of React components, such as the current authenticated user, theme, or preferred language.

How to Create and Use React Context

  1. Create a Context: Use React.createContext() to create a context object. The context object comes with a Provider and a Consumer, but in modern React, the useContext hook is often used instead of the Consumer.

    import React from 'react'; const ThemeContext = React.createContext('light');
  2. Provide Context: Use a Provider to make the context value available to all children components.

    function App() { return ( <ThemeContext.Provider value="dark"> <Toolbar /> </ThemeContext.Provider> ); }
  3. Consume Context: Access the context value using the useContext hook.

    import React, { useContext } from 'react'; function Toolbar() { const theme = useContext(ThemeContext); return <div style={{ background: theme === 'dark' ? '#333' : '#FFF' }}>Toolbar</div>; }

Benefits of Using React Context

  • Efficiency: Avoids prop drilling, making it easier to manage states that need to be accessed by many components.
  • Clarity: Context can make your app's structure more intuitive by grouping related values.

Considerations

While context is powerful, it should be used sparingly as it can make component reuse more complex. For small to medium-sized applications, it works well, but for more extensive state management, libraries like Redux might be more suitable.

Struggling to find common date to meet with your friends? Try our new tool commondate.xyz
devFlipCards 2025

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.

Struggling to find common date to meet with your friends? Try our new tool
commondate.xyz