DEV Community

Josh Love
Josh Love

Posted on

React Pattern Question

Hey there,

I have been trying out the new React hooks, and I ended up coming to a point where a component has it's own store and actions baked into itself and the parent can access those as needed.

The use case: There is a need to display the data from my component or have the ability to trigger functions from the parent (without having to go through a library like redux).

My Question: Is this an okay set up for a component in React or is it an anti-pattern?

The Code (working jsfiddle):

import React, { useState } from 'react';

const ChildComponent = (prop1) => {
  const [myCustomValue, updateMyCustomValue] = useState(0);

  const myCustomAction = () => {
    updateMyCustomValue(myCustomValue + 1);
  }

  const view = () => (
    <input type="button" onClick={myCustomAction} value={`${myCustomValue} - ${prop1}`} />
  );

  return {
    store: myCustomValue,
    actions: myCustomAction,
    view,
  };
};

const ParentComponent = () => {
  const prop1 = 'test';

  const Test1 = ChildComponent(prop1);

  return (
    <div>
      <div>
        <h2>Component Default View</h2>
        <Test1.view />
        <h2>Parent can also trigger updates and show data from component</h2>
        <input type="button" onClick={Test1.actions} value={Test1.store} />
      </div>
    </div>
  );
}

Top comments (1)

Collapse
 
simpgeek profile image
Nigel Kirby

Check into reactjs.org/docs/hooks-faq.html#ho...

Set state and actions in the parent if the parent needs to know them.