How to pass setstate as props typescript

To pass setState as a prop in TypeScript, you need to define the prop type as a function that takes the new state value as an argument and returns void. Here’s how you can do it:

ChildComponent.tsx

      
        import React from 'react';

        type ChildProps = {
          setStateProp: (newState: any) => void;
        };

        const ChildComponent: React.FC<ChildProps> = ({ setStateProp }) => {
          const handleClick = () => {
            const newState = { key: 'value' };
            setStateProp(newState);
          };

          return (
            <button onClick={handleClick}>Update Parent State</button>
          );
        };

        export default ChildComponent;
      
    

ParentComponent.tsx

      
        import React, { useState } from 'react';
        import ChildComponent from './ChildComponent';

        const ParentComponent: React.FC = () => {
          const [state, setState] = useState<any>();

          const handleSetState = (newState: any) => {
            setState(newState);
          };

          return (
            <div>
              <h1>Parent Component</h1>
              
              <p>Current State: {JSON.stringify(state)}</p>
              <ChildComponent setStateProp={handleSetState} />
            </div>
          );
        };

        export default ParentComponent;
      
    

In the above example, the ChildComponent takes a prop called setStateProp, which is of type (newState: any) => void. This means it expects a function that accepts a new state value and returns void.

When the button is clicked in the ChildComponent, it calls the handleClick function, where a new state object is created. Then, it calls the setStateProp function (passed as a prop) with the new state object as an argument.

In the ParentComponent, the handleSetState function receives the new state object as an argument and updates the state using the setState hook.

This way, you can pass the setState function as a prop to child components in TypeScript and update the parent state.

Leave a comment