createContext

Advertisement

  • We¬†can¬†create¬†global¬†state¬†to¬†access¬†across¬†diff.¬†components¬†with¬†**”Context¬†API”**.
  • We¬†can¬†use¬†`createContext()`¬†funtion¬†to¬†create¬†the¬†context.
  • Wrap¬†the¬†`<App>`¬†component¬†with¬†`<ThemeContext.Provider¬†value={{¬†textColor:¬†‘red’¬†}}>`¬†to¬†pass¬†the¬†`textColor`¬†to¬†all¬†inner¬†`App`¬†components.
  • Inside¬†`<App>`¬†component¬†we¬†have¬†`<Welcome>`¬†component.
  • So,¬†We¬†can¬†access¬†`textColor`¬†into¬†`<Welcome>`¬†component¬†with¬†`<ThemeContext.Consumer>`
  • Inside¬†`<ThemeContext.Consumer>`¬†we¬†have¬†a¬†callback¬†function¬†in¬†which¬†we¬†extract¬†the¬†`textColor`.
  • And¬†finally¬†we¬†use¬†it¬†to¬†set¬†the¬†text¬†color¬†to¬†our¬†`<h2>`¬†tag¬†with¬†`style={{¬†color:¬†textColor¬†}}`.

E.g.

We have created a `ThemeContext` context with `createContext()`.

import React, { createContext } from 'react';

// Theme context, default to light theme
const ThemeContext = createContext();

const Welcome = () => {
	return (
		<ThemeContext.Consumer>
			{ ( {textColor} ) => {
				return(
					<h2 style={{ color: textColor }}>Hello World</h2>
				)}
			}
		</ThemeContext.Consumer>
	)
}

const App = () => {
	return (
		<ThemeContext.Provider value={{ textColor: 'red' }}>
			<Welcome />
		</ThemeContext.Provider>
	)
}

export default App;
%d bloggers like this: