A collection of 0posts

    React Hooks Memo

    React Hooks.

    A note on React Hooks, which can turn the function components in React into something powerful

    With class components, you have to be very conscious of the fact that your coding is distributed, which makes it difficult to touch the code.

    Hooks is designed to allow a single Hooks to be used for each function, making it easier to understand the role of each code when additions and modifications are made.

    Types of Hooks

    There are various types of Hooks, and the main hooks are noted here.


    The useState hook returns State and the functions that update it.

    tsx:title=Sample const [state, setState] = useState(initialState)

    At the first render, state shall be set to the value of initialState.
    If you want to update the value of state, use setState to set it.

    This will update the value of state to the value of newState.

    tsx:title=sample const Counter: React.FC = initialState => { const [count, setCount] = useState(initialCount) return ( <> Count: {count} <button onClick={() => setCount(initialCount)}>Reset <button onClick={() => setCount(prevCount => prevCount - 1)}>- <button onClick={() => setCount(prevCount => prevCount + 1)}>+ </> ) }

    ### useEffect.
    Hooks to write a process with side effects
    useEffect is executed after the render is reflected.

    In useEffect, the second argument of useEffect is used to handle conditional side effects. The argument must contain an array.

    If this array is updated, the operation in useEffect is performed again.

    If the second argument is an empty array, useEffect shall be executed only at the first render. If the second argument is an empty array, it is executed only on the first render.

    tsx:title=Sample useEffect() => { const subscription = props.source.subscribe() return () => { subscription.unsubscribe() } }, [props.source])

    ### useContext.
    Hooks to receive the return value of React.createContext
    If MyContext.Provider is updated, this hook will be added to its Generate the render again using the value passed to MyContext.
    const themes = {
      light: {
        foreground: "#000000",
        background: "#eeeeeeee",
      dark: {
        foreground: "#ffffff",
        background: "#222222",
    const ThemeContext = React.createContext( themes.light)
    const App: React.FC = () => {
      return (
        <ThemeContext.Provider value={themes.dark}>
          <Toolbar />
    const Toolbar: React.FC = props => {
      return (
          <ThemedButton />.
    const ThemedButton: React.FC = () => {
      const theme = useContext(ThemeContext)
      return (
        <button style={{ background: theme.background, color: theme.foreground }}
          I am styled by theme context!

    Notes on using Hooks

    When using Hooks, the order in which Hooks are executed should not be reversed in some cases.

    RELATEDLatest Articles
    © Abakry. All rights reserved.