useState
const [state, setState] = useState(initialState);
Functional updates
function Counter({initialCount}) {
const [count, setCount] = useState(initialCount);
return (
<>
Count: {count}
<button onClick={() => setCount(initialCount)}>Reset</button>
<button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
</>
);
}
Lazy initial state
If the initial state is the result of an expensive computation, you may provide a function instead, which will be executed only on the initial render.
const [state, setState] = useState(() => {
const initialState = someExpensiveComputation(props);
return initialState;
});
useEffect
useEffect(didUpdate)
The clean-up function runs before the component is removed from the UI to prevent memory leaks. Additionally, if a component renders multiple times, the previous effect is cleaned up before executing the next effect.
useEffect(() => {
const subscription = props.source.subscribe();
// Cleaning up an effect
return () => {
subscription.unsubscribe();
};
// Conditionally firing an effect
}, [props.source]
);
useContext
const value = useContext(MyContext);
Accepts a context object (the value return from React.createContext) and returns the current context value for that context. The current context value is determined by the value prop of the nearest <MyContext.Provider> above the calling component in the tree.
const themes = {
light: {
foreground: '#000000',
background: '#eeeeee'
},
dark: {
foreground: '#ffffff',
background: '#222222'
}
};
const ThemeContext = React.createContext(themes.light);
function App() {
return (
<ThemeContext.Provider value={themes.dark}>
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar(props) {
return (
<div>
<ThemedButton />
</div>
);
}
function ThemedButton() {
const theme = useContext(ThemeContext);
return (
<button style={{ background: theme.background, color: theme.foreground }}>
I am styled by theme context!
</button>
);
}
网友评论