Master React.js: Components for Modern Web
Sobre a Aula

Global State Management

In global state management in React, you can centralize shared data among multiple components. This is useful for avoiding excessive prop drilling.

A common example is using Context API or Redux. With Context API, you create a context for the data and make it available to all descendant components.

This reduces the need to manually pass props at various levels of the component tree. For example:

// Creating a context
const MyContext = React.createContext();

// Context provider to wrap components
function MyProvider({ children }) {
  const [state, setState] = useState(initialState);

  return (
    <MyContext.Provider value={{ state, setState }}>
      {children}
    </MyContext.Provider>
  );
}

// Consuming context in a component
function MyComponent() {
  const { state, setState } = useContext(MyContext);

  return (
    <div>
      <p>The global state is: {state}</p>
      <button onClick={() => setState(newState)}>Update State</button>
    </div>
  );
}

This approach simplifies access and updating of state throughout the application, making maintenance and development easier.

In summary, global state management in React offers an effective solution for sharing data between components without the need to manually pass props, improving project organization and structure.

Entrar na conversa
Rolar para cima