Skip to main content

Command Palette

Search for a command to run...

useContext | React Hooks

Updated
1 min readView as Markdown
useContext | React Hooks

Redux manage the global state but useState() and useReducer() manage the local state in the component. So Redux is a global state manager.

ContextAPI is same as Redux , but it's built-in in React , and it has a different syntax.

the context consumer component can be used in both functional and class based component.

what is the solution for the consumer long term ?

Example:

<AuthContext.Consumer>
      {(ctx) =>
        <nav className={classes.nav}>
          <ul>
            {ctx.isLoggedIn && (
              <li>
                <a href="/">Users</a>
              </li>
            )}
          </ul>
        </nav>

      }
</AuthContext.Consumer>

Solution:

function User() { 
const ctx = useContext(UserContext);

    return (
        <nav className={classes.nav}>
          <ul>
            {ctx.isLoggedIn && (
              <li>
                <a href="/">Users</a>
              </li>
            )}
          </ul>
        </nav>
       }
     )

}

Screenshot (193).png

Screenshot (194).png

==================================

Screenshot (195).png

Screenshot (196).png

=============================================

Screenshot (197).png

Screenshot (198).png

Note : *AuthContext: Auth-Context is not a component

AuthContext.Provider : Auth-Context provider is a component we can use in our JSX code, and we can wrap it around other components and those other components and all their descendant components. *

Screenshot (204).png

Screenshot (205).png

D

Thanks for explanation 👍

More from this blog

Omar's blog

135 posts