Using Prototypes in React State

I’m trying to use prototypes to make looking up data from a deeply nested object easier. The issue is, when I use lodash’s cloneDeep function the prototype chain is broken ( I’m pretty sure ). I’m using the cloneDeep function to make sure not to mutate the state directly.

Before waisting anyone’s time with some of the code from the project, is this an okay practice? Is it correct to do something the following or should prototypes be avoided when storing objects in state?

const parent = { a: { b: { c: null }}}
const child = Object.create(parent)
parent.a.b.c = child

this.setState({ parent }) 

Thank you in advance for the help 🙂

2 thoughts on “Using Prototypes in React State”

  1. I would second-take any deeply nested abstraction used as state. Your state should be as flat as possible. Nesting makes for really buggy code, and updating becomes a monumental task.

    constructor() {
        this.state = {foo: 'bar', a: 1, b: 2}
    handleEvent(event) {
        this.setState({ ...this.state, foo: })
    render() {
        const { foo, a, b } = this.state
        // ...

    This isn’t really the direction React is moving though. I would suggest having a look at the latest release notes.

  2. a) I’d suggest to use typescript instead of proptypes. It’s more powerful and efficient.

    b) You don’t need lodash to deep clone an object. Just do:

    const objectA = {name: "Joe", age: 44}
    const clonedObjectA = {...objectA}
    // mutate clonedObject "Paul", 
    console.log("objectA", objectA) // original untouched
    console.log("clonedObjectA", clonedObjectA) // new Object mutated

    Then you can perform mutations on clonedObjectA without worrying about objectA.

    c) when mutating a state, you can simply use prevState like this:

    const [state, setState] = useState({})
    const mutateState = (key, value) => {
    setState(prevState=> ({...prevState, key: value}))

Leave a Comment