📜  context api react ts - TypeScript (1)

📅  最后修改于: 2023-12-03 14:40:12.501000             🧑  作者: Mango

Context API with React and TypeScript

React Context API is a way to manage state sharing in a React application without the need to pass down props through multiple levels or implementing a state management library like Redux.

Why use Context API?
  • Avoids prop drilling i.e., passing props down through many levels of components.
  • Simplifies state management and sharing of state between components.
  • Reduces redundancy by wrapping a set of components with context that provides access to the same shared state.
Basics of Context API

Context API consists of two parts: Provider and Consumer.

Provider

The Provider component defines the context and provides the state or data to React components that are interested in it.

First, we need to create a new context with the createContext function provided by React. We can initialize it with an initial state of our choice, which is optional.

import React from 'react';

interface IUserContext {
  firstName: string;
  lastName: string;
}

const userContext = React.createContext<IUserContext | null>(null);

Next, we need to set the initial state for our context and make it available to the components that need it using the Provider component.

import { useState } from 'react';

const App = () => {
  const [user, setUser] = useState<IUserContext>({ firstName: 'John', lastName: 'Doe' });

  return (
    <userContext.Provider value={{ user, setUser }}>
      // Your app components
    </userContext.Provider>
  );
};
Consumer

The Consumer component reads the context and re-renders the component tree when the context changes.

To use the Consumer, we need to access the context using the useContext hook provided by React.

import React, { useContext } from 'react';

const ChildComponent = () => {
  const { user, setUser } = useContext(userContext);

  const updateUser = () => {
    setUser({ firstName: 'Jane', lastName: 'Doe' });
  };

  return (
    <>
      <p>Name: {user?.firstName} {user?.lastName}</p>
      <button onClick={updateUser}>Update User</button>
    </>
  );
};
Conclusion

Context API provides an efficient way to share data across components without the need for props drilling, thus making the development process easier.

This is just a basic introduction to Context API in React with TypeScript, but you can extend it with your own complex data structures and render it with your own React components.