Skip to the content.

Hooks and Context

back to main

context behavior

Step One: Initiate Context

Let's create them:

const UserProvider = ({ children }) => {
  // User is the name of the "data" that gets stored in context
  const [user, setUser] = useState({ name: '', auth: true });

  // Login updates the user data with a name parameter
  const login = (name) => {
    setUser((user) => ({
      name: name,
      auth: true,
    }));
  };

  // Logout updates the user data to default
  const logout = () => {
    setUser((user) => ({
      name: '',
      auth: false,
    }));
  };

  return (
    <UserContext.Provider value=>
      {children}
    </UserContext.Provider>
  );
}

Step Three: Implement Context in our App

ReactDOM.render( document.getElementById(‘root’) );

**Step Four: Update Context**

- From here on out, we're going to be consuming context (i.e. using and updating it). Using context just requires importing it and calling it! In App.js, we import it as well as authenticated and unauthenticated components.
```js
import React, { useContext } from 'react';
import { UserContext } from './UserContext';
import AuthApp from './AuthApp';
import UnauthApp from './UnauthApp';

function App() {
  const { user } = useContext(UserContext);

  return user.auth ? <AuthApp /> : <UnauthApp />;
}

export default App;

function AuthApp() { const { user, logout } = useContext(UserContext);

return ( <> <h1>Hello, {user.name}!</h1> <button onClick={logout}>Logout</button> </> ); }

export default AuthApp; UnauthApp.js import React, { useContext, useState } from ‘react’; import { UserContext } from ‘./UserContext’;

function UnauthApp() { const { login } = useContext(UserContext); const [name, setName] = useState();

return ( <> <h1>Please, log in!</h1>

  <label>Name:</label>
  <input
    type="text"
    onChange={(event) => {
      setName(event.target.value);
    }}
  />
  <button onClick={() => login(name)}>Log in</button>
</>   ); }

export default UnauthApp; ```