Let me explain you UseContext...!

·

1 min read

As you already know, React uses state to store data and props to pass data between components. This works well for handling local state and for passing simple props between parent/child components. This system breaks down when you start to have global state or props that need to be passed to deeply nested components.

This is where the Context API comes in. With the context API you can specify certain pieces of data that will be available to all components nested inside the context with no need to pass this data through each component.

const ThemeContext = React.createContext()

function App() { const [theme, setTheme] = useState('dark')

return (

<ThemeContext.Provider value={{ theme, setTheme }}>

  <ChildComponent />

</ThemeContext.Provider>

) }

This is how you create a useContextProvider which can be used in other screens.

For using the context in your screen you should do it using use context

function HomeScreen (){ const {setTheme}= useContext(ThemeContext)

setTheme('light')}> }

When you will execute the above function what it will exactly do is change the theme in the useState from 'dark' to 'light'.

Thats how useContext works to manage the global state across all pages

Hope you enjoyed reading it..!