Skip to content

Instantly share code, notes, and snippets.

@Steve2955
Last active April 19, 2022 05:24
Show Gist options
  • Save Steve2955/ba3c23c9f012e74c9548d5e723b2e8e9 to your computer and use it in GitHub Desktop.
Save Steve2955/ba3c23c9f012e74c9548d5e723b2e8e9 to your computer and use it in GitHub Desktop.
My React Learnings

React Learnings

  • npx create-react-app <folder-name>
  • parentheses after return-statements are used so js won't insert semicolons automatically

Props

Are used to pass data from parent to child

class Child extends React.Component {
  render(){
    return(
      <p>{this.props.value}</p>
    );
  }
}

class Parent extends React.Component {
  render(){
    return(
      <div>
        <Child value="I was passed as a prop!"/>
      </div>
    );
  }
}
  • props can be functions as well

State

State stores the private data of a component

classes are old fashioned, use modern hooks instead

class SomeButton extends React.Component {
  // using state requires a constructor for defining an initial state
  constructor(props) {
    super(props);
    this.state = {
      value: 'Click me',
    }
  }
  render() {
    return (
      // setState changes the internal data of the component and forces it to re-render
      <button onClick={()=>this.setState({value: 'Clicked!!!'})}>
        {this.state.value}
      </button>
    );
  }
}

changing state of complex objects

  • detecting changes in complex objects is hard.
  • that's why react recommends using immutability over mutatability
handleClick(i) {
  // Create a copy of the array
  const squares = this.state.squares.slice();
  squares[i] = 'X';
  this.setState({squares: squares});
}

Hooks

Hooks always start with use[...]

useState

const [count, setCount] = useState(0);

useEffect

useEffect(() => {
  console.log('Component has been mounted!')
});

Examples

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment