DEV Community

loading...

React Tips and Tricks You May Have Missed

aumayeung profile image John Au-Yeung Originally published at thewebdev.info ・4 min read

Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62

Subscribe to my email list now at http://jauyeung.net/subscribe/

React is the most used front end library for building modern, interactive front end web apps. It can also be used to build mobile apps. In this article, we’ll look at some tips and tricks to make building apps with React easier.

Use React Hooks In Functional Components

Hooks make React function components smart. Without hooks, all we can use function components to display data. That’s why they were also called stateless components. With hooks, they have their own internal state and methods, which make them much more useful.

For instance, we can write components with hooks as follows:

import React from "react";

export default function App() {
  const [count, setCount] = React.useState(0);
  return (
    <div className="App">
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <p>{count}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In the code above, we have the built-in React useState hook which lets us change the count state with the setCount function.

We call setCount with an argument to update the value as we did with the onClick handler.

It looks simple. We don’t have to reference this as we do with class components, so we don’t have call bind to set the right this as we do with class components.

It’s just much cleaner to work with. We can also write our own hooks to update data our way.

Function components don’t have access to lifecycle methods, so this is the way to make smart function components.

Use The React Context API For Passing Props

The React context API lets us pass data between unrelated components. With function components we can use the createContext method to create a context. We can use the returned component to wrap around our components which we want to share data between.

Then we can pass any data that we want between them. The communication is still one way. Data is passed from context provider to consumer.

For instance, we can write the following code to pass data between them:

import React from "react";
const CountContext = React.createContext(0);

function Count() {
  const count = React.useContext(CountContext);
  return <p>{count}</p>;
}

export default function App() {
  const [count, setCount] = React.useState(0);
  return (
    <CountContext.Provider value={count}>
      <div className="App">
        <button onClick={() => setCount(count + 1)}>Increment</button>
        <Count />
      </div>
    </CountContext.Provider>
  );
}
Enter fullscreen mode Exit fullscreen mode

In the code above, we created a React with React.createContext so that we can share data with the Count component.

We use the CountContext.Provider component to wrap it around everything. Then we pass in the count variable into as the value of the value prop, which will share it with any component that calls React.useContext and is inside the CountContext.Provider component.

Then in Count , we call React.useContext with our CountContext passed in. Therefore, the count will be passed from App in Count via the value prop and rendered in Count .

Therefore, when we click the Increment, then the count value will increase.

Styled Components

One benefit of using React is it’s very easy to set CSS values in JS. Therefore, it’s very easy to make styled-components with CSS inside components, making them self contained.

We can use the style-components library to make styled-components easily. It comes with template tags that turns CSS strings we pass in into a component.

For instance, we can write the following:

import React from "react";
import styled from "styled-components";

const Div = styled.div`
  background: ${props => (props.primary ? "green" : "white")};
  color: ${props => props.color};

margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid green;
`;

export default function App() {
  return (
    <div className="App">
      <Div background="green" color="white" primary={true}>
        foo
      </Div>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In the code above, we have the props in the template string, which are props that we pass in when we use the component. style.div is a template tag. Template tags are functions that take in a template string and return some objects on our choice.

In this case, we return a styled component. style.div returns a div with the types that we hard code or set according to props.

Then when we reference Div in App , we’ll see a green box with white text as we specified with the color prop. Since we specified that the value of the primary prop is true , style-component will set the background color to green.

Conclusion

The hooks API makes React components cleaner and easier to understand. It lets us make function components smart. We also don’t have to worry about the value of this or lifecycle hooks any more.

The context API is useful for sharing data between 2 components, regardless of their relationship. We can use the useContext hook to do the sharing.

Finally, the styled-components library comes with template tags to let us make styled-components with ease.

Discussion (0)

pic
Editor guide