Conteúdo do curso
React.js: Understand and Apply the Lifecycle
Sobre a Aula

Local and global state management

To create efficient React applications, it’s essential to understand how to manage state, both locally and globally.

Local State in Components

In React, local state is managed using the useState hook. It allows you to add state to functional components. Here’s a simple example:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click here
      </button>
    </div>
  );
}

In this example, count is the local state and setCount is the function to update it. Always use useState for states that are specific to a component.

Global State with Context API

For states that need to be shared across components, React’s Context API is useful. It allows you to create a global context that can be accessed by nested components. Here’s a basic example:

import React, { createContext, useContext, useState } from 'react';

const ThemeContext = createContext('light');

function App() {
  const [theme, setTheme] = useState('dark');

  return (
    <ThemeContext.Provider value={theme}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar() {
  const theme = useContext(ThemeContext);

  return (
    <div>
      <p>The current theme is: {theme}</p>
    </div>
  );
}

In this example, ThemeContext.Provider sets up the global context with the theme value, which is accessed in Toolbar using useContext.

When to Use Global State vs Local State

Use local state (useState) for data that is specific to a component and doesn’t need to be shared with others.

Use global state (Context API) for data that needs to be accessed by multiple components or nested components.

Conclusion

Mastering state management is crucial for building scalable and efficient React applications. Practice using useState for local states and explore the Context API for global states. This will help you structure your components in an organized and maintainable way.

Entrar na conversa
Rolar para cima