How to convert prevState of class component into functional component

32 Views Asked by At

Below is a class based component example

class TestContainer extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            attached: initializeObject(props.TestTransactions),
            numTrue: props.TestTransactions.length,
        };
    }
    commonSetState = () => {
        this.setState((prevState) => ({
            attached: {
                ...prevState.attached,
                ...initializeObject(this.props.newTransactions),
            },
            numTrue: prevState.numTrue + this.props.newTransactions.length,
        }));
    };

How do i convert the above commonSetState method if i need to convert this complete component as a functional component

2

There are 2 best solutions below

0
shruti On

To transform your class component's commonSetState into a functional component format, you can use the useState hook from React like so:

import React, { useState } from 'react';

function TestContainer({ TestTransactions, newTransactions }) {
    const [attached, updateAttached] = useState(initializeObject(TestTransactions));
    const [numTrue, updateNumTrue] = useState(TestTransactions.length);

    const commonSetState = () => {
        updateAttached(current => ({
            ...current,
            ...initializeObject(newTransactions),
        }));
        updateNumTrue(current => current + newTransactions.length);
    };

    // Your component logic continues here...
}
2
Jakub Kotrs On

The useState hook in a function component works very similarly to state in a class component. You have the option to have a lazy initialization by passing in a function that returns initial state and also have the option to change the state using a state updater function

// useState(fn) for lazy initialization
const [state, setState] = useState(() => ({
    attached: initializeObject(props.TestTransactions),
    numTrue: props.TestTransactions.length,
)})

const commonSetState = () => {
    // setState(fn) for state updater with access to previous state
    setState((prevState) => ({
        attached: {
            ...prevState.attached,
            ...initializeObject(props.newTransactions),
        },
        numTrue: prevState.numTrue + props.newTransactions.length,
    }))
}