usecontext react code example
Example 1: useRef
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
Example 2: usecontext hook
import React, { useContext } from "react";
import ColorContext from "./colorcontex.ts";
const MyComponent = () => {
const colors = useContext(ColorContext);
return <div style={{ backgroundColor: colors.blue }}>...</div>;
};import React, { useContext } from "react";
const MyComponent = () => {
const colors = useContext(ColorContext);
return <div style={{ backgroundColor: colors.blue }}>...</div>;
};
Example 3: usereducer
function init(initialCount) { return {count: initialCount};}
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
case 'reset': return init(action.payload); default:
throw new Error();
}
}
function Counter({initialCount}) {
const [state, dispatch] = useReducer(reducer, initialCount, init); return (
<>
Count: {state.count}
<button
onClick={() => dispatch({type: 'reset', payload: initialCount})}> Reset
</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}
Example 4: react usecontext examples
import React from "react";
import ReactDOM from "react-dom";
const NumberContext = React.createContext();
function App() {
return (
<NumberContext.Provider value={42}>
<div>
<Display />
</div>
</NumberContext.Provider>
);
}
function Display() {
return (
<NumberContext.Consumer>
{value => <div>The answer is {value}.</div>}
</NumberContext.Consumer>
);
}
ReactDOM.render(<App />, document.querySelector("#root"));
import React, { useContext } from 'react';
function Display() {
const value = useContext(NumberContext);
return <div>The answer is {value}.</div>;
}
Example 5: usereducer
const [state, dispatch] = useReducer(
reducer,
{count: initialCount} );